﻿// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include "SplitDemo.h"
#include "PropSheetSetting.h"
#include "MainFrm.h"

#include <wchar.h>
#include "DeviceSelectDialog.h"
#include <dbt.h>
#include "CyAPI.h"
#include "Cfile64.h"
#include "ProgressBar.h"
#include "PrjSaveDialog.h"
#include "PrjLoadDialog.h"

#include "AUTOSEQDIALOG.h"
#include "windows.h"
#include "winbase.h"
#include "CCyjpswDialog.h"
#include "RemoteCtrlDlg.h"
#include "GNPropSheet.h"
#include "PCOMM.H"
#include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include "AutoCntDialog.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#include <ImageHlp.h>  
#pragma comment(lib,"imagehlp.lib")  
#define THDLY 50
void CMainFrame::OnUpdataToolBarBtn(CCmdUI* pCmdUI)
{
	
	pCmdUI->Enable(m_bEnableBtn);

}
void CMainFrame::SetBtnSatate(BOOL bEnabl)
{
	m_bEnableBtn = bEnabl;
}
// CMainFrame

IMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
	ON_WM_CREATE()
	ON_WM_SETFOCUS()	
	ON_COMMAND(ID_MENU_FUN1, &CMainFrame::OnMenuFun1)
	ON_COMMAND(ID_MENU_FUN2, &CMainFrame::OnMenuFun2)

	ON_COMMAND(ID_MENU_FUN4, &CMainFrame::OnMenuFun4)
	ON_COMMAND(ID_MENU_FUN5, &CMainFrame::OnMenuFunCancel)
	ON_UPDATE_COMMAND_UI(ID_MENU_FUN5, &CMainFrame::OnUpdateMenuCancel)
	ON_COMMAND(ID_MENU_FUN6, &CMainFrame::OnMenuPrjSave)
	ON_COMMAND(ID_MENU_FUN7, &CMainFrame::OnMenuPrjLoad)
	ON_COMMAND(ID_MENU_FUN8, &CMainFrame::OnMenuAutoRun)
	ON_UPDATE_COMMAND_UI(ID_MENU_FUN8, &CMainFrame::OnUpdateMenuAutoRun)
	ON_COMMAND(ID_MENU_FUN9, &CMainFrame::OnMenuAutoSeq)
	ON_COMMAND(ID_MENU_FUN10, &CMainFrame::OnMenuBufEdit)
	ON_COMMAND(ID_MENU_FUN11, &CMainFrame::OnMenuRemoteControl)
	ON_COMMAND(ID_MENU_FUN12, &CMainFrame::OnMenuGeneralSetting)
	ON_COMMAND(ID_MENU_FUN13, &CMainFrame::OnMenuHelp)
	//ON_NOTIFY(TBN_DROPDOWN, AFX_IDW_TOOLBAR, OnToolbarDropDown)
	ON_NOTIFY_EX(TTN_NEEDTEXT, 0, OnToolTipNotify)


	ON_WM_SIZE()
	ON_WM_TIMER()

	ON_WM_CLOSE()
	ON_COMMAND(ID_MENU0_BUF0, &CMainFrame::OnMenu0Buf0)
	ON_COMMAND(ID_MENU0_BUF1, &CMainFrame::OnMenu0Buf1)
	ON_COMMAND(ID_MENU0_BUF2, &CMainFrame::OnMenu0Buf2)
	ON_COMMAND(ID_MENU0_BUF3, &CMainFrame::OnMenu0Buf3)
	ON_COMMAND(ID_MENU0_BUF4, &CMainFrame::OnMenu0Buf4)
	ON_COMMAND(ID_MENU0_BUF5, &CMainFrame::OnMenu0Buf5)
	ON_COMMAND(ID_MENU0_BUF6, &CMainFrame::OnMenu0Buf6)
	ON_COMMAND(ID_MENU0_BUF7, &CMainFrame::OnMenu0Buf7)
	ON_COMMAND(ID_MENU0_BUF8, &CMainFrame::OnMenu0Buf8)
	ON_COMMAND(ID_MENU0_BUF9, &CMainFrame::OnMenu0Buf9)
	ON_MESSAGE(WM_COMM_RXSTR, &CMainFrame::OnReceiveStrSerialNet)
	ON_MESSAGE(WM_COMM_BALL0, &CMainFrame::OnSetBalls0)
	ON_MESSAGE(WM_COMM_BALL1, &CMainFrame::OnSetBalls1)
	ON_MESSAGE(WM_COMM_BALL2, &CMainFrame::OnSetBalls2)
	ON_MESSAGE(WM_COMM_BALL3, &CMainFrame::OnSetBalls3)
	ON_MESSAGE(WM_COMM_BALL4, &CMainFrame::OnSetBalls4)
	ON_MESSAGE(WM_COMM_BALL5, &CMainFrame::OnSetBalls5)
	ON_MESSAGE(WM_COMM_BALL6, &CMainFrame::OnSetBalls6)
	ON_MESSAGE(WM_COMM_BALL7, &CMainFrame::OnSetBalls7)
	ON_MESSAGE(WM_COMM_BALL8, &CMainFrame::OnSetBalls8)
	ON_MESSAGE(WM_COMM_BALL9, &CMainFrame::OnSetBalls9)
	ON_MESSAGE(WM_COMM_OPENBALLDLG, &CMainFrame::OnOpenBallDlg)
	ON_COMMAND(ID_LANGUAGE_CHINESE, &CMainFrame::OnLanguageChinese)
	ON_COMMAND(ID_LANGUAGE_ENGLISH, &CMainFrame::OnLanguageEnglish)
	ON_COMMAND(ID_FILE_LOADFILE, &CMainFrame::OnFileLoadfile)
	ON_COMMAND(ID_MRU1, &CMainFrame::OnMru1)
	ON_COMMAND(ID_MRU2, &CMainFrame::OnMru2)
	ON_COMMAND(ID_MRU3, &CMainFrame::OnMru3)
	ON_COMMAND(ID_MRU4, &CMainFrame::OnMru4)
	ON_COMMAND(ID_MRU5, &CMainFrame::OnMru5)
	ON_COMMAND(ID_MRU6, &CMainFrame::OnMru6)
	ON_COMMAND(ID_MRU7, &CMainFrame::OnMru7)
	ON_COMMAND(ID_MRU8, &CMainFrame::OnMru8)
	ON_COMMAND(ID_PROGRAMERCOUNT_1, &CMainFrame::OnProgramercount1)
	ON_COMMAND(ID_PROGRAMERCOUNT_2, &CMainFrame::OnProgramercount2)
	
	ON_COMMAND(ID_PROGRAMERCOUNT_4, &CMainFrame::OnProgramercount4)

	ON_COMMAND(ID_PROGRAMERCOUNT_6, &CMainFrame::OnProgramercount6)
	ON_COMMAND(ID_GETFIMRWAREVERSION, &CMainFrame::OnGetFirmware)
	ON_COMMAND(ID_PROJECT_LOADPROJECT, &CMainFrame::OnProjectLoadproject)
	ON_COMMAND(ID_PROJECT_SAVEPROJECT, &CMainFrame::OnProjectSaveproject)
	ON_COMMAND(ID_MENU_DEVICELIST, &CMainFrame::OnDeviceList)

	ON_COMMAND(ID_ACCELERATOR32852, &CMainFrame::OnAccelerator32852)
	ON_COMMAND(ID_ACCELERATORCYJ, &CMainFrame::OnAcceleratorCYJ)
	ON_COMMAND(ID_ACCELERATORCYJ1, &CMainFrame::OnAcceleratorCYJ1)
	ON_UPDATE_COMMAND_UI(ID_MENU_FUN13,&CMainFrame::OnUpdataToolBarBtn)
	ON_COMMAND(ID_SETTING_UPDATEFIRMWARE, &CMainFrame::OnUpdateFirmware)
	ON_COMMAND(ID_MENU_UPDATEDRIVER, &CMainFrame::OnUpdateUsbDrv)
	ON_COMMAND(ID_LOGSUMARY, &CMainFrame::OnLogsumary)
END_MESSAGE_MAP()



UCHAR SocMap1[][1] = { 4 };
UCHAR SocMap2[][2] = { { 4, 2 }, \
					{4, 7} };
UCHAR SocMap4[][4] = { { 4, 7, 2, 1 }, \
//TSOP48 下面4个SOCKET加密芯片
						{4, 6, 7, 5} };
#ifndef ONLINE
UCHAR SocMap8[][8] = { 4, 6, 7, 5, \
						2, 0, 1, 3, };
#else
UCHAR SocMap8[][8] = { 0, 1, 2, 3, \
						4, 5, 6, 7 };
#endif
static UINT indicators[] =
{
	ID_SEPARATOR,           // status line indicator
	ID_INDICATOR_CAPS,

};

// CMainFrame construction/destruction
extern UCHAR gSendbuf[16 * 1024 * 1024];

void DllDispMsg(TCHAR *swzPtr)
{
	CMainFrame * pMainFrame = (CMainFrame *)AfxGetApp()->m_pMainWnd; 
	pMainFrame->pFormView3->RichEditShow(0, swzPtr, COLOR_YELLOW, 0, 0);
}

#include "shlwapi.h"

#pragma comment(lib,"shlwapi.lib")
const wchar_t* wcstrrchr(const wchar_t* str, const wchar_t wc)
{
	const wchar_t* pwc = NULL;
	for (int i = wcslen(str) - 1; i >= 0; i--)
	{
		if (str[i] == wc)
		{
			pwc = str + i;
			break;
		}
	}
	return pwc;
}

bool createMultiDir(const wchar_t* path)
{
	if (path == NULL) return false;
	const wchar_t* pwcStrrchr = wcstrrchr(path, L'\\');
	if (!pwcStrrchr) return false;
	if (PathIsDirectory(path)) return true;

	wchar_t wsSubPath[MAX_PATH] = {};
	memset(wsSubPath, 0, sizeof(wsSubPath));
	for (int i = 0; i < pwcStrrchr - path; i++)
		wsSubPath[i] = *(path + i);
	createMultiDir(wsSubPath);
	if (CreateDirectory(path, NULL)) return true;
	return false;
}


CMainFrame::CMainFrame()
{

	memset(&stu_AdptNearLmtDlgTime, 0, sizeof(stu_AdptNearLmtDlgTime));
	memset(nAutoLoopFirst, 0, sizeof(nAutoLoopFirst));
	nAutoSenseAutoRunStartEnd = 0;
	nAutoSenseAutoRun = 0;
	stu_deviceifo_bak.nDevIdx = -1;
	m_nChecksumType = 0;
	pHlpDlg = NULL;
	m_bEnableBtn = FALSE;
	CString strtmp;
	TCHAR wszTemp[MAX_PATH];
	m_nCYJPSD = 0;
	memset(m_swzHuaJieLogPath, 0, sizeof(m_swzHuaJieLogPath));
	memset(m_FailSktLastAuto, 0, sizeof(m_FailSktLastAuto));

	memset(m_wszPrjPathSubDirInIni, 0, sizeof(m_wszPrjPathSubDirInIni));
	memset(m_wArrCheckPinVols, 0, sizeof(m_wArrCheckPinVols));
	memset(m_szVCC, 0, sizeof(m_szVCC));
	memset(m_szVIO, 0, sizeof(m_szVIO));
	m_nBtnIdx = 0xff;
	m_hDeviceNotify = NULL;
	int i;
	g_nCustomerDef = 0;
	m_strC_F_FileModifyTime.Empty();
	nFirstShowFMVersion = 0;
	memset(m_nIsAuto, 0, sizeof(m_nIsAuto));
	m_strCurBtn=L"";
	memset(&stu_AutoSeq, 0, sizeof(stu_AutoSeq));
	memset(&stu_FuncList, 0, sizeof(stu_FuncList));
	memset(&stu_AutoSeqGlob, 0, sizeof(stu_AutoSeqGlob));
	memset(llCheckSumFile, 0, sizeof(llCheckSumFile));
	memset(llCheckSumBuf, 0, sizeof(llCheckSumBuf));
	memset(szRemoteRespBuf, 0, sizeof(szRemoteRespBuf));

	memset(&stu_LogStatus, 0, sizeof(stu_LogStatus));
	memset(&stu_BlkTbl, 0, sizeof(stu_BlkTbl));
	m_nIsReadFitnessNeedDataAnalysis = 0;
	m_nIsLoadBufferDll = 0;
	memset(&stu_overlap, 0, sizeof(stu_overlap));
	memset(&stu_overlapini, 0, sizeof(stu_overlapini));
	memset(m_szSkipSokEncSN, 0, sizeof(m_szSkipSokEncSN));
	m_nRDskipSokEncSN = 0;
	i = 0;
	
	memset(m_nInvalidProgSnTime, 0, sizeof(m_nInvalidProgSnTime));
	strcpy(m_szSkipSokEncSN[i++], "0000000000000031");
	strcpy(m_szSkipSokEncSN[i++], "0000000000000026");
	strcpy(m_szSkipSokEncSN[i++], "0000000000000029");
	//strcpy(m_szSkipSokEncSN[i++], "0000000000000011");
	strcpy(m_szSkipSokEncSN[i++], "0000100000000096");
	strcpy(m_szSkipSokEncSN[i++], "0000000000000076");
	strcpy(m_szSkipSokEncSN[i++], "0000100000000100");
	strcpy(m_szSkipSokEncSN[i++], "0000100000000163");

	//strcpy(m_szSkipSokEncSN[i++], "0000100000000134");
	strcpy(m_szSkipSokEncSN[i++], "0000100000000227");
	strcpy(m_szSkipSokEncSN[i++], "0000100000000277");

	strcpy(m_szSkipSokEncSN[i++], "0000100000000179");
	//客户原厂。不检查适配器号
	strcpy(m_szSkipSokEncSN[i++], "0000100000000182");

	strcpy(m_szSkipSokEncSN[i++], "0000100000000103");

	//strcpy(m_szSkipSokEncSN[i++], "0000100000000238");
	strcpy(m_szSkipSokEncSN[i++], "0000100000000104");
	strcpy(m_szSkipSokEncSN[i++], "0000000000000090");
	//memset(m_nFileSelType, 0, sizeof(m_nFileSelType));
	

	for (i = 0; i < BUFNUM; i++)
	{
		strtmp.Format(L"%s", g_wszCurPath);
		strtmp += L"lib\\Rbuf";
		strtmp.AppendFormat(L"%d", i);
		m_strReadFileDefaultPath[i] = strtmp;
	}
	


	memset(m_cArrCheckPinStats, 0, sizeof(m_cArrCheckPinStats));

	m_hAccel = ::LoadAccelerators(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_ACCELERATOR1));
	memset(m_nAutoCntPressure, 0, sizeof(m_nAutoCntPressure));
	m_nIsDataLoaded = 0;

	m_nIsSnNeed = 1;
	m_strCurJsonFile=L"";

	m_strJsonPath = L"c:\\";
	m_strProgFilePath = L"c:\\";
	int j = 0;
	m_cCurProcFunIdx=0;
	m_bCreateClient = 0;
	n_IsInRTCSetting = 0;

	m_nAlgoLen=0;
	m_nFpga0Len_320=0;
	m_nFpga1Len_320=0;	
	m_bIsPrjEditable =TRUE;

	
	memset(m_nSiteNo, 0, sizeof(m_nSiteNo));
	memset(&stu_ProgLocList, 0, sizeof(stu_ProgLocList));
	MruFile.ReadProgLocation(stu_ProgLocList.szProgLocList,m_nSiteNo);


	memset(m_cDownData,0,sizeof(m_cDownData));
	memset(&stu_GenSetting, 0, sizeof(stu_GenSetting));
	memset(&stu_UserSNProg, 0, sizeof(stu_UserSNProg));
	memset(g_SerialResBuf, 0, sizeof(g_SerialResBuf));
	
	for (i = 0; i < PROGRAMERMAXNUM; i++)
	{
		m_strSktNearLmt[i].Empty();
		hEvent[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
		hEvent1[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
		m_pThreadUsbData[i] = NULL;
		m_pThreadUserProc1[i] = NULL;
		//m_nSlectedUSBDeviceOpen[i] = 0;

		stu_UsbDeviceArr[i].pUsbDevice = NULL;
		stu_UsbDeviceArr[i].status = USBNOTCONNECT;
		stu_UsbDeviceArr[i].nUsbOpenIdx = 0xffffffff;
		memset(stu_UsbDeviceArr[i].serialNO, 0, sizeof(stu_UsbDeviceArr[i].serialNO));
		
		stu_UsbDeviceArr[i].curSocketUnit = 0;
		stu_UsbDeviceArr[i].nIsProgChecked = 1;
		stu_UsbDeviceArr[i].nSockProgStatus = 0;
		stu_UsbDeviceArr[i].nIsInRemoteRunning = 0;
		
		for (j = 0; j < sizeof(stu_UsbDeviceArr[i].CtrlIDarr) / sizeof(stu_UsbDeviceArr[i].CtrlIDarr[0]); j++)
		{
			stu_UsbDeviceArr[i].CtrlIDarr[j] = 0;
		}
		memset(stu_UsbDeviceArr[i].nSokFailCnt, 0, sizeof(stu_UsbDeviceArr[i].nSokFailCnt));
		memset(stu_UsbDeviceArr[i].nSokTotalCnt, 0, sizeof(stu_UsbDeviceArr[i].nSokTotalCnt));
		stu_UsbDeviceArr[i].nTotalFailCnt = 0;
		stu_UsbDeviceArr[i].nTotalCnt = 0;
	}
	//teset
	//stu_UsbDeviceArr[0].pUsbDevice = (CCyUSBDevice *)1;


	CtrlIDDef();

	
	m_nCurDevNo = 0;
	m_strDeviceData = L"";
	m_pThread  = NULL;
	memset(&stu_ProjectHead,0, sizeof(stu_ProjectHead));
	stu_ProjectHead.nHeadLen=sizeof(stu_ProjectHead);

	memset(m_ullRealFileSize, 0, sizeof(m_ullRealFileSize));

	TCHAR swztemp[MAX_PATH];
	
	wcscpy_s(swztemp, g_wszCurPath);
	wcscat_s(swztemp, L"setting.ini");
	g_nCustomerDef = GetPrivateProfileInt(L"ProgInfo", L"Customer", 0, swztemp);
	stu_overlapini.nIsOverLapCheck=GetPrivateProfileInt(L"OverLapCheck", L"OverLapCheckEn", 0, swztemp);

	stu_overlapini.nOverLapCheckIdx = GetPrivateProfileInt(L"OverLapCheck", L"OverLapCheckIdx", 0, swztemp);

	if(CUSTOMERDEF_HUAJIE == g_nCustomerDef)
	{
		GetPrivateProfileString(_T("ProgInfo"), L"CustomerLogPath", L"", m_swzHuaJieLogPath, MAX_PATH, swztemp);
		if (wcslen(m_swzHuaJieLogPath))
		{
			wcscpy(wszTemp, m_swzHuaJieLogPath);
			//创建路径要\\结尾
			if(wcscmp(&wszTemp[wcslen(wszTemp) - 1], L"\\"))
			{
				wcscat(wszTemp, L"\\");
			}
			
			
			if (!PathIsDirectory(wszTemp))
			{

				CreateDirectory(wszTemp, NULL);
				MakeSureDirectoryPathExists((LPCSTR)CStringA(wszTemp));
			}
			Sleep(1);
			if (!PathIsDirectory(wszTemp))
			{
				AfxMessageBox(L"Log 路径创建失败");
			}

		}
	}
	
	
	m_bAutoMenuEnable = FALSE;

	stu_progdll.pDispMsg = DllDispMsg;
	stu_dlfiledll.pDispMsg = DllDispMsg;
	stu_dlfiledll.pParentWnd = this;
	memset(m_cComboBufSelMap, 255, sizeof(m_cComboBufSelMap));

	memset(m_szHuaJiBoardSN, 0, sizeof(m_szHuaJiBoardSN));
	strcpy(m_szHuaJiBoardSN[0], "0000000000000001");
	strcpy(m_szHuaJiBoardSN[1], "0000000000000002");
	strcpy(m_szHuaJiBoardSN[2], "0000000000000003");
	strcpy(m_szHuaJiBoardSN[3], "0000000000000004");
	memset(m_wszHuaJiBoardTime, 0, sizeof(m_wszHuaJiBoardTime));

	CSktNMMap.RemoveAll();
	


#ifndef ONLINE
	CreateCSktNMMap();
//	int j = 0;
	//以下保证CLEAR 和SOCKET 密号都有

	for (i = 0; i < g_nDevInfoCnt; i++)
	{
		for (j = 0; j < 4; j++)
		{
			//有SOCKET密号，无CLEAR
			if ((strlen(pstuDevInfo[i].szSocketName[j])) && (0 == strlen(pstusktname[i].szSocketNameClear[j])))
			{
				CharToTchar(wszTemp, pstuDevInfo[i].szSocketName[j]);
				CSktNMMap.Lookup(wszTemp, strtmp);
				if (0 == strtmp.IsEmpty())
				{
					TcharToChar(pstusktname[i].szSocketNameClear[j], strtmp.GetBuffer());
				}
			}
			//有CLEAR ,无对应密号
			else if ((0==strlen(pstuDevInfo[i].szSocketName[j])) && (strlen(pstusktname[i].szSocketNameClear[j])))
			{
				CharToTchar(wszTemp, pstusktname[i].szSocketNameClear[j]);
				CSktNMMap1.Lookup(wszTemp, strtmp);
				if (0 == strtmp.IsEmpty())
				{
					TcharToChar(pstuDevInfo[i].szSocketName[j], strtmp.GetBuffer());
				}
			}
		}
	
	}


#endif

	wcscpy_s(swztemp, g_wszCurPath);
	wcscat_s(swztemp, L"setting.ini");
	GetPrivateProfileString(L"Path", L"PrjPathSubDir", L"", m_wszPrjPathSubDirInIni, sizeof(m_wszPrjPathSubDirInIni), swztemp);
	if (m_wszPrjPathSubDirInIni[wcslen(m_wszPrjPathSubDirInIni)-1] == L'\\')
	{
		m_wszPrjPathSubDirInIni[wcslen(m_wszPrjPathSubDirInIni) - 1] = 0;
	}
	if (wcslen(m_wszPrjPathSubDirInIni))
	{
		wcscpy_s(swztemp, g_wszCurPath);
		wcscat(swztemp, L"Log\\Prj\\");
		wcscat(swztemp, m_wszPrjPathSubDirInIni);
		if (!PathIsDirectory(swztemp))
		{
			::CreateDirectory(swztemp, 0);
		}
	}
	
	m_strChipSel_PrjName=L"";
	m_nChipSel_Prj = 0;
	m_dllhandleConnectDlg = NULL;
	if (50==g_nDebugValue)
	{
		m_dllhandleConnectDlg = LoadLibrary(L"connectdlg.dll");
		
	}
	//自动加载文件状态
	m_nTimeState = 0;
	//m_nCYJPSD = 1;
}
/*
void CMainFrame::GetSpartan3aFpgaType()
{
	

}
*/
int CMainFrame::CreateCSktNMMap()
{
	CStdioFile fSktNM;
	CString strSktNMMapFile = g_wszCurPath, strSktNMMapFile_ = g_wszCurPath;
	CString strTmp;
	int i,j;
	CSktNMMap.RemoveAll();
	CSktNMMap1.RemoveAll();

	TCHAR wszSkt[30], wszSktShow[30];
	char sztemp[256];
	TCHAR wsztemp[1024];
	strSktNMMapFile += L"lib\\Mp";
	strSktNMMapFile_ += L"lib\\Mp_";
	DecodeXor(strSktNMMapFile_, strSktNMMapFile);
	if (fSktNM.Open(strSktNMMapFile_, CFile::modeRead) == FALSE)
	{
		AfxMessageBox(L"open Mp fail");
		return -1;
	}
	while (fSktNM.ReadString(wsztemp, sizeof(wsztemp)))
	{
		if (wcslen(wsztemp) < 20)break;
		_stscanf(wsztemp, _T("%s	%s"), wszSkt, wszSktShow);
		TcharToChar(sztemp, wszSktShow);
		str_toupper(sztemp);
		CharToTchar(wszSktShow, sztemp);
		CSktNMMap.SetAt(wszSkt, wszSktShow);
		CSktNMMap1.SetAt(wszSktShow, wszSkt);

	}

	fSktNM.Close();
	DeleteFile(strSktNMMapFile_);

	for (int i = 0; i < g_nDevInfoCnt; i++)
	{
		for (j = 0; j < 4; j++)
		{
			
			if ((strlen(pstusktname[i].szSocketNameClear[j])) && (0 == strlen(pstuDevInfo[i].szSocketName[j])))
			{
				//有clear没有密文
				CharToTchar(wsztemp, pstusktname[i].szSocketNameClear[j]);
				CSktNMMap1.Lookup(wsztemp,  strTmp);
				TcharToChar(pstuDevInfo[i].szSocketName[j], strTmp.GetBuffer());

			}
			if ((0==strlen(pstusktname[i].szSocketNameClear[j])) && (strlen(pstuDevInfo[i].szSocketName[j])))
			{
				//有密文没有clear
				CharToTchar(wsztemp, pstuDevInfo[i].szSocketName[j]);
				CSktNMMap.Lookup(wsztemp, strTmp);
				TcharToChar(pstusktname[i].szSocketNameClear[j], strTmp.GetBuffer());
				
			}
		}
	}
	return 0;
}
void CMainFrame::CtrlIDDef()
{

	
	
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
	{
		//8个STATIC颜色

		stu_UsbDeviceArr[0].CtrlIDarr[1] = IDC_MODULE0_ICO0;
		stu_UsbDeviceArr[0].CtrlIDarr[2] = IDC_MODULE0_ICO1;
		stu_UsbDeviceArr[0].CtrlIDarr[3] = IDC_MODULE0_ICO2;
		stu_UsbDeviceArr[0].CtrlIDarr[4] = IDC_MODULE0_ICO3;
		stu_UsbDeviceArr[0].CtrlIDarr[5] = IDC_MODULE0_ICO4;
		stu_UsbDeviceArr[0].CtrlIDarr[6] = IDC_MODULE0_ICO5;
		stu_UsbDeviceArr[0].CtrlIDarr[7] = IDC_MODULE0_ICO6;
		stu_UsbDeviceArr[0].CtrlIDarr[8] = IDC_MODULE0_ICO7;
		
		
		//8个SOCKETCHK
		
		stu_UsbDeviceArr[0].CtrlIDarr[9] = IDC_MODLE0_SOKCHK0;
		stu_UsbDeviceArr[0].CtrlIDarr[10] = IDC_MODLE0_SOKCHK1;
		stu_UsbDeviceArr[0].CtrlIDarr[11] = IDC_MODLE0_SOKCHK2;
		stu_UsbDeviceArr[0].CtrlIDarr[12] = IDC_MODLE0_SOKCHK3;
		stu_UsbDeviceArr[0].CtrlIDarr[13] = IDC_MODLE0_SOKCHK4;
		stu_UsbDeviceArr[0].CtrlIDarr[14] = IDC_MODLE0_SOKCHK5;
		stu_UsbDeviceArr[0].CtrlIDarr[15] = IDC_MODLE0_SOKCHK6;
		stu_UsbDeviceArr[0].CtrlIDarr[16] = IDC_MODLE0_SOKCHK7;

		//8个STATIC颜色
		stu_UsbDeviceArr[1].CtrlIDarr[1] = IDC_MODULE1_ICO0;
		stu_UsbDeviceArr[1].CtrlIDarr[2] = IDC_MODULE1_ICO1;
		stu_UsbDeviceArr[1].CtrlIDarr[3] = IDC_MODULE1_ICO2;
		stu_UsbDeviceArr[1].CtrlIDarr[4] = IDC_MODULE1_ICO3;
		stu_UsbDeviceArr[1].CtrlIDarr[5] = IDC_MODULE1_ICO4;
		stu_UsbDeviceArr[1].CtrlIDarr[6] = IDC_MODULE1_ICO5;
		stu_UsbDeviceArr[1].CtrlIDarr[7] = IDC_MODULE1_ICO6;
		stu_UsbDeviceArr[1].CtrlIDarr[8] = IDC_MODULE1_ICO7;

		//8个SOCKETCHK
		stu_UsbDeviceArr[1].CtrlIDarr[9] = IDC_MODLE1_SOKCHK0;
		stu_UsbDeviceArr[1].CtrlIDarr[10] = IDC_MODLE1_SOKCHK1;
		stu_UsbDeviceArr[1].CtrlIDarr[11] = IDC_MODLE1_SOKCHK2;
		stu_UsbDeviceArr[1].CtrlIDarr[12] = IDC_MODLE1_SOKCHK3;
		stu_UsbDeviceArr[1].CtrlIDarr[13] = IDC_MODLE1_SOKCHK4;
		stu_UsbDeviceArr[1].CtrlIDarr[14] = IDC_MODLE1_SOKCHK5;
		stu_UsbDeviceArr[1].CtrlIDarr[15] = IDC_MODLE1_SOKCHK6;
		stu_UsbDeviceArr[1].CtrlIDarr[16] = IDC_MODLE1_SOKCHK7;
		//8个STATIC颜色
		stu_UsbDeviceArr[2].CtrlIDarr[1] = IDC_MODULE2_ICO0;
		stu_UsbDeviceArr[2].CtrlIDarr[2] = IDC_MODULE2_ICO1;
		stu_UsbDeviceArr[2].CtrlIDarr[3] = IDC_MODULE2_ICO2;
		stu_UsbDeviceArr[2].CtrlIDarr[4] = IDC_MODULE2_ICO3;
		stu_UsbDeviceArr[2].CtrlIDarr[5] = IDC_MODULE2_ICO4;
		stu_UsbDeviceArr[2].CtrlIDarr[6] = IDC_MODULE2_ICO5;
		stu_UsbDeviceArr[2].CtrlIDarr[7] = IDC_MODULE2_ICO6;
		stu_UsbDeviceArr[2].CtrlIDarr[8] = IDC_MODULE2_ICO7;

		//8个SOCKETCHK
		stu_UsbDeviceArr[2].CtrlIDarr[9] =  IDC_MODLE2_SOKCHK0;
		stu_UsbDeviceArr[2].CtrlIDarr[10] = IDC_MODLE2_SOKCHK1;
		stu_UsbDeviceArr[2].CtrlIDarr[11] = IDC_MODLE2_SOKCHK2;
		stu_UsbDeviceArr[2].CtrlIDarr[12] = IDC_MODLE2_SOKCHK3;
		stu_UsbDeviceArr[2].CtrlIDarr[13] = IDC_MODLE2_SOKCHK4;
		stu_UsbDeviceArr[2].CtrlIDarr[14] = IDC_MODLE2_SOKCHK5;
		stu_UsbDeviceArr[2].CtrlIDarr[15] = IDC_MODLE2_SOKCHK6;
		stu_UsbDeviceArr[2].CtrlIDarr[16] = IDC_MODLE2_SOKCHK7;

		//8个STATIC颜色
		stu_UsbDeviceArr[3].CtrlIDarr[1] = IDC_MODULE3_ICO0;
		stu_UsbDeviceArr[3].CtrlIDarr[2] = IDC_MODULE3_ICO1;
		stu_UsbDeviceArr[3].CtrlIDarr[3] = IDC_MODULE3_ICO2;
		stu_UsbDeviceArr[3].CtrlIDarr[4] = IDC_MODULE3_ICO3;
		stu_UsbDeviceArr[3].CtrlIDarr[5] = IDC_MODULE3_ICO4;
		stu_UsbDeviceArr[3].CtrlIDarr[6] = IDC_MODULE3_ICO5;
		stu_UsbDeviceArr[3].CtrlIDarr[7] = IDC_MODULE3_ICO6;
		stu_UsbDeviceArr[3].CtrlIDarr[8] = IDC_MODULE3_ICO7;

		//8个SOCKETCHK
		stu_UsbDeviceArr[3].CtrlIDarr[9] = IDC_MODLE3_SOKCHK0;
		stu_UsbDeviceArr[3].CtrlIDarr[10] = IDC_MODLE3_SOKCHK1;
		stu_UsbDeviceArr[3].CtrlIDarr[11] = IDC_MODLE3_SOKCHK2;
		stu_UsbDeviceArr[3].CtrlIDarr[12] = IDC_MODLE3_SOKCHK3;
		stu_UsbDeviceArr[3].CtrlIDarr[13] = IDC_MODLE3_SOKCHK4;
		stu_UsbDeviceArr[3].CtrlIDarr[14] = IDC_MODLE3_SOKCHK5;
		stu_UsbDeviceArr[3].CtrlIDarr[15] = IDC_MODLE3_SOKCHK6;
		stu_UsbDeviceArr[3].CtrlIDarr[16] = IDC_MODLE3_SOKCHK7;

		//8个STATIC颜色
		stu_UsbDeviceArr[4].CtrlIDarr[1] = IDC_MODULE4_ICO0;
		stu_UsbDeviceArr[4].CtrlIDarr[2] = IDC_MODULE4_ICO1;
		stu_UsbDeviceArr[4].CtrlIDarr[3] = IDC_MODULE4_ICO2;
		stu_UsbDeviceArr[4].CtrlIDarr[4] = IDC_MODULE4_ICO3;
		stu_UsbDeviceArr[4].CtrlIDarr[5] = IDC_MODULE4_ICO4;
		stu_UsbDeviceArr[4].CtrlIDarr[6] = IDC_MODULE4_ICO5;
		stu_UsbDeviceArr[4].CtrlIDarr[7] = IDC_MODULE4_ICO6;
		stu_UsbDeviceArr[4].CtrlIDarr[8] = IDC_MODULE4_ICO7;

		//8个SOCKETCHK
		stu_UsbDeviceArr[4].CtrlIDarr[9] = IDC_MODLE4_SOKCHK0;
		stu_UsbDeviceArr[4].CtrlIDarr[10] = IDC_MODLE4_SOKCHK1;
		stu_UsbDeviceArr[4].CtrlIDarr[11] = IDC_MODLE4_SOKCHK2;
		stu_UsbDeviceArr[4].CtrlIDarr[12] = IDC_MODLE4_SOKCHK3;
		stu_UsbDeviceArr[4].CtrlIDarr[13] = IDC_MODLE4_SOKCHK4;
		stu_UsbDeviceArr[4].CtrlIDarr[14] = IDC_MODLE4_SOKCHK5;
		stu_UsbDeviceArr[4].CtrlIDarr[15] = IDC_MODLE4_SOKCHK6;
		stu_UsbDeviceArr[4].CtrlIDarr[16] = IDC_MODLE4_SOKCHK7;

		//8个STATIC颜色
		stu_UsbDeviceArr[5].CtrlIDarr[1] = IDC_MODULE5_ICO0;
		stu_UsbDeviceArr[5].CtrlIDarr[2] = IDC_MODULE5_ICO1;
		stu_UsbDeviceArr[5].CtrlIDarr[3] = IDC_MODULE5_ICO2;
		stu_UsbDeviceArr[5].CtrlIDarr[4] = IDC_MODULE5_ICO3;
		stu_UsbDeviceArr[5].CtrlIDarr[5] = IDC_MODULE5_ICO4;
		stu_UsbDeviceArr[5].CtrlIDarr[6] = IDC_MODULE5_ICO5;
		stu_UsbDeviceArr[5].CtrlIDarr[7] = IDC_MODULE5_ICO6;
		stu_UsbDeviceArr[5].CtrlIDarr[8] = IDC_MODULE5_ICO7;

		//8个SOCKETCHK
		stu_UsbDeviceArr[5].CtrlIDarr[9] = IDC_MODLE5_SOKCHK0;
		stu_UsbDeviceArr[5].CtrlIDarr[10] = IDC_MODLE5_SOKCHK1;
		stu_UsbDeviceArr[5].CtrlIDarr[11] = IDC_MODLE5_SOKCHK2;
		stu_UsbDeviceArr[5].CtrlIDarr[12] = IDC_MODLE5_SOKCHK3;
		stu_UsbDeviceArr[5].CtrlIDarr[13] = IDC_MODLE5_SOKCHK4;
		stu_UsbDeviceArr[5].CtrlIDarr[14] = IDC_MODLE5_SOKCHK5;
		stu_UsbDeviceArr[5].CtrlIDarr[15] = IDC_MODLE5_SOKCHK6;
		stu_UsbDeviceArr[5].CtrlIDarr[16] = IDC_MODLE5_SOKCHK7;

		//8个STATIC颜色
		stu_UsbDeviceArr[6].CtrlIDarr[1] = IDC_MODULE6_ICO0;
		stu_UsbDeviceArr[6].CtrlIDarr[2] = IDC_MODULE6_ICO1;
		stu_UsbDeviceArr[6].CtrlIDarr[3] = IDC_MODULE6_ICO2;
		stu_UsbDeviceArr[6].CtrlIDarr[4] = IDC_MODULE6_ICO3;
		stu_UsbDeviceArr[6].CtrlIDarr[5] = IDC_MODULE6_ICO4;
		stu_UsbDeviceArr[6].CtrlIDarr[6] = IDC_MODULE6_ICO5;
		stu_UsbDeviceArr[6].CtrlIDarr[7] = IDC_MODULE6_ICO6;
		stu_UsbDeviceArr[6].CtrlIDarr[8] = IDC_MODULE6_ICO7;

		//8个SOCKETCHK
		stu_UsbDeviceArr[6].CtrlIDarr[9] = IDC_MODLE6_SOKCHK0;
		stu_UsbDeviceArr[6].CtrlIDarr[10] = IDC_MODLE6_SOKCHK1;
		stu_UsbDeviceArr[6].CtrlIDarr[11] = IDC_MODLE6_SOKCHK2;
		stu_UsbDeviceArr[6].CtrlIDarr[12] = IDC_MODLE6_SOKCHK3;
		stu_UsbDeviceArr[6].CtrlIDarr[13] = IDC_MODLE6_SOKCHK4;
		stu_UsbDeviceArr[6].CtrlIDarr[14] = IDC_MODLE6_SOKCHK5;
		stu_UsbDeviceArr[6].CtrlIDarr[15] = IDC_MODLE6_SOKCHK6;
		stu_UsbDeviceArr[6].CtrlIDarr[16] = IDC_MODLE6_SOKCHK7;

		//8个STATIC颜色
		stu_UsbDeviceArr[7].CtrlIDarr[1] = IDC_MODULE7_ICO0;
		stu_UsbDeviceArr[7].CtrlIDarr[2] = IDC_MODULE7_ICO1;
		stu_UsbDeviceArr[7].CtrlIDarr[3] = IDC_MODULE7_ICO2;
		stu_UsbDeviceArr[7].CtrlIDarr[4] = IDC_MODULE7_ICO3;
		stu_UsbDeviceArr[7].CtrlIDarr[5] = IDC_MODULE7_ICO4;
		stu_UsbDeviceArr[7].CtrlIDarr[6] = IDC_MODULE7_ICO5;
		stu_UsbDeviceArr[7].CtrlIDarr[7] = IDC_MODULE7_ICO6;
		stu_UsbDeviceArr[7].CtrlIDarr[8] = IDC_MODULE7_ICO7;

		//8个SOCKETCHK
		stu_UsbDeviceArr[7].CtrlIDarr[9] = IDC_MODLE7_SOKCHK0;
		stu_UsbDeviceArr[7].CtrlIDarr[10] = IDC_MODLE7_SOKCHK1;
		stu_UsbDeviceArr[7].CtrlIDarr[11] = IDC_MODLE7_SOKCHK2;
		stu_UsbDeviceArr[7].CtrlIDarr[12] = IDC_MODLE7_SOKCHK3;
		stu_UsbDeviceArr[7].CtrlIDarr[13] = IDC_MODLE7_SOKCHK4;
		stu_UsbDeviceArr[7].CtrlIDarr[14] = IDC_MODLE7_SOKCHK5;
		stu_UsbDeviceArr[7].CtrlIDarr[15] = IDC_MODLE7_SOKCHK6;
		stu_UsbDeviceArr[7].CtrlIDarr[16] = IDC_MODLE7_SOKCHK7;

		if (PROGRAMERMAXNUM > 8)
		{
	
		//8个STATIC颜色
		stu_UsbDeviceArr[8].CtrlIDarr[1] = IDC_MODULE8_ICO0;
		stu_UsbDeviceArr[8].CtrlIDarr[2] = IDC_MODULE8_ICO1;
		stu_UsbDeviceArr[8].CtrlIDarr[3] = IDC_MODULE8_ICO2;
		stu_UsbDeviceArr[8].CtrlIDarr[4] = IDC_MODULE8_ICO3;
		stu_UsbDeviceArr[8].CtrlIDarr[5] = IDC_MODULE8_ICO4;
		stu_UsbDeviceArr[8].CtrlIDarr[6] = IDC_MODULE8_ICO5;
		stu_UsbDeviceArr[8].CtrlIDarr[7] = IDC_MODULE8_ICO6;
		stu_UsbDeviceArr[8].CtrlIDarr[8] = IDC_MODULE8_ICO7;

		//8个SOCKETCHK
		stu_UsbDeviceArr[8].CtrlIDarr[9] =  IDC_MODLE8_SOKCHK0;
		stu_UsbDeviceArr[8].CtrlIDarr[10] = IDC_MODLE8_SOKCHK1;
		stu_UsbDeviceArr[8].CtrlIDarr[11] = IDC_MODLE8_SOKCHK2;
		stu_UsbDeviceArr[8].CtrlIDarr[12] = IDC_MODLE8_SOKCHK3;
		stu_UsbDeviceArr[8].CtrlIDarr[13] = IDC_MODLE8_SOKCHK4;
		stu_UsbDeviceArr[8].CtrlIDarr[14] = IDC_MODLE8_SOKCHK5;
		stu_UsbDeviceArr[8].CtrlIDarr[15] = IDC_MODLE8_SOKCHK6;
		stu_UsbDeviceArr[8].CtrlIDarr[16] = IDC_MODLE8_SOKCHK7;

		//8个STATIC颜色
		stu_UsbDeviceArr[9].CtrlIDarr[1] = IDC_MODULE9_ICO0;
		stu_UsbDeviceArr[9].CtrlIDarr[2] = IDC_MODULE9_ICO1;
		stu_UsbDeviceArr[9].CtrlIDarr[3] = IDC_MODULE9_ICO2;
		stu_UsbDeviceArr[9].CtrlIDarr[4] = IDC_MODULE9_ICO3;
		stu_UsbDeviceArr[9].CtrlIDarr[5] = IDC_MODULE9_ICO4;
		stu_UsbDeviceArr[9].CtrlIDarr[6] = IDC_MODULE9_ICO5;
		stu_UsbDeviceArr[9].CtrlIDarr[7] = IDC_MODULE9_ICO6;
		stu_UsbDeviceArr[9].CtrlIDarr[8] = IDC_MODULE9_ICO7;

		//8个SOCKETCHK
		stu_UsbDeviceArr[9].CtrlIDarr[9] = IDC_MODLE9_SOKCHK0;
		stu_UsbDeviceArr[9].CtrlIDarr[10] = IDC_MODLE9_SOKCHK1;
		stu_UsbDeviceArr[9].CtrlIDarr[11] = IDC_MODLE9_SOKCHK2;
		stu_UsbDeviceArr[9].CtrlIDarr[12] = IDC_MODLE9_SOKCHK3;
		stu_UsbDeviceArr[9].CtrlIDarr[13] = IDC_MODLE9_SOKCHK4;
		stu_UsbDeviceArr[9].CtrlIDarr[14] = IDC_MODLE9_SOKCHK5;
		stu_UsbDeviceArr[9].CtrlIDarr[15] = IDC_MODLE9_SOKCHK6;
		stu_UsbDeviceArr[9].CtrlIDarr[16] = IDC_MODLE9_SOKCHK7;
		}
	}
	else
	{
		//8个STATIC颜色
		stu_UsbDeviceArr[0].CtrlIDarr[1] = IDC_MODULE0_ICO4;
		stu_UsbDeviceArr[0].CtrlIDarr[2] = IDC_MODULE0_ICO5;
		stu_UsbDeviceArr[0].CtrlIDarr[3] = IDC_MODULE0_ICO6;
		stu_UsbDeviceArr[0].CtrlIDarr[4] = IDC_MODULE0_ICO7;
		stu_UsbDeviceArr[0].CtrlIDarr[5] = IDC_MODULE0_ICO0;
		stu_UsbDeviceArr[0].CtrlIDarr[6] = IDC_MODULE0_ICO1;
		stu_UsbDeviceArr[0].CtrlIDarr[7] = IDC_MODULE0_ICO2;
		stu_UsbDeviceArr[0].CtrlIDarr[8] = IDC_MODULE0_ICO3;

		//8个SOCKETCHK
		stu_UsbDeviceArr[0].CtrlIDarr[9] = IDC_MODLE0_SOKCHK4;
		stu_UsbDeviceArr[0].CtrlIDarr[10] = IDC_MODLE0_SOKCHK5;
		stu_UsbDeviceArr[0].CtrlIDarr[11] = IDC_MODLE0_SOKCHK6;
		stu_UsbDeviceArr[0].CtrlIDarr[12] = IDC_MODLE0_SOKCHK7;
		stu_UsbDeviceArr[0].CtrlIDarr[13] = IDC_MODLE0_SOKCHK0;
		stu_UsbDeviceArr[0].CtrlIDarr[14] = IDC_MODLE0_SOKCHK1;
		stu_UsbDeviceArr[0].CtrlIDarr[15] = IDC_MODLE0_SOKCHK2;
		stu_UsbDeviceArr[0].CtrlIDarr[16] = IDC_MODLE0_SOKCHK3;

		//8个STATIC颜色
		stu_UsbDeviceArr[1].CtrlIDarr[1] = IDC_MODULE1_ICO4;
		stu_UsbDeviceArr[1].CtrlIDarr[2] = IDC_MODULE1_ICO5;
		stu_UsbDeviceArr[1].CtrlIDarr[3] = IDC_MODULE1_ICO6;
		stu_UsbDeviceArr[1].CtrlIDarr[4] = IDC_MODULE1_ICO7;
		stu_UsbDeviceArr[1].CtrlIDarr[5] = IDC_MODULE1_ICO0;
		stu_UsbDeviceArr[1].CtrlIDarr[6] = IDC_MODULE1_ICO1;
		stu_UsbDeviceArr[1].CtrlIDarr[7] = IDC_MODULE1_ICO2;
		stu_UsbDeviceArr[1].CtrlIDarr[8] = IDC_MODULE1_ICO3;

		//8个SOCKETCHK
		stu_UsbDeviceArr[1].CtrlIDarr[9] = IDC_MODLE1_SOKCHK4;
		stu_UsbDeviceArr[1].CtrlIDarr[10] = IDC_MODLE1_SOKCHK5;
		stu_UsbDeviceArr[1].CtrlIDarr[11] = IDC_MODLE1_SOKCHK6;
		stu_UsbDeviceArr[1].CtrlIDarr[12] = IDC_MODLE1_SOKCHK7;
		stu_UsbDeviceArr[1].CtrlIDarr[13] = IDC_MODLE1_SOKCHK0;
		stu_UsbDeviceArr[1].CtrlIDarr[14] = IDC_MODLE1_SOKCHK1;
		stu_UsbDeviceArr[1].CtrlIDarr[15] = IDC_MODLE1_SOKCHK2;
		stu_UsbDeviceArr[1].CtrlIDarr[16] = IDC_MODLE1_SOKCHK3;

		//8个STATIC颜色
		stu_UsbDeviceArr[2].CtrlIDarr[1] = IDC_MODULE2_ICO4;
		stu_UsbDeviceArr[2].CtrlIDarr[2] = IDC_MODULE2_ICO5;
		stu_UsbDeviceArr[2].CtrlIDarr[3] = IDC_MODULE2_ICO6;
		stu_UsbDeviceArr[2].CtrlIDarr[4] = IDC_MODULE2_ICO7;
		stu_UsbDeviceArr[2].CtrlIDarr[5] = IDC_MODULE2_ICO0;
		stu_UsbDeviceArr[2].CtrlIDarr[6] = IDC_MODULE2_ICO1;
		stu_UsbDeviceArr[2].CtrlIDarr[7] = IDC_MODULE2_ICO2;
		stu_UsbDeviceArr[2].CtrlIDarr[8] = IDC_MODULE2_ICO3;

		//8个SOCKETCHK
		stu_UsbDeviceArr[2].CtrlIDarr[9] = IDC_MODLE2_SOKCHK4;
		stu_UsbDeviceArr[2].CtrlIDarr[10] = IDC_MODLE2_SOKCHK5;
		stu_UsbDeviceArr[2].CtrlIDarr[11] = IDC_MODLE2_SOKCHK6;
		stu_UsbDeviceArr[2].CtrlIDarr[12] = IDC_MODLE2_SOKCHK7;
		stu_UsbDeviceArr[2].CtrlIDarr[13] = IDC_MODLE2_SOKCHK0;
		stu_UsbDeviceArr[2].CtrlIDarr[14] = IDC_MODLE2_SOKCHK1;
		stu_UsbDeviceArr[2].CtrlIDarr[15] = IDC_MODLE2_SOKCHK2;
		stu_UsbDeviceArr[2].CtrlIDarr[16] = IDC_MODLE2_SOKCHK3;

		//8个STATIC颜色
		stu_UsbDeviceArr[3].CtrlIDarr[1] = IDC_MODULE3_ICO4;
		stu_UsbDeviceArr[3].CtrlIDarr[2] = IDC_MODULE3_ICO5;
		stu_UsbDeviceArr[3].CtrlIDarr[3] = IDC_MODULE3_ICO6;
		stu_UsbDeviceArr[3].CtrlIDarr[4] = IDC_MODULE3_ICO7;
		stu_UsbDeviceArr[3].CtrlIDarr[5] = IDC_MODULE3_ICO0;
		stu_UsbDeviceArr[3].CtrlIDarr[6] = IDC_MODULE3_ICO1;
		stu_UsbDeviceArr[3].CtrlIDarr[7] = IDC_MODULE3_ICO2;
		stu_UsbDeviceArr[3].CtrlIDarr[8] = IDC_MODULE3_ICO3;

		//8个SOCKETCHK
		stu_UsbDeviceArr[3].CtrlIDarr[9] = IDC_MODLE3_SOKCHK4;
		stu_UsbDeviceArr[3].CtrlIDarr[10] = IDC_MODLE3_SOKCHK5;
		stu_UsbDeviceArr[3].CtrlIDarr[11] = IDC_MODLE3_SOKCHK6;
		stu_UsbDeviceArr[3].CtrlIDarr[12] = IDC_MODLE3_SOKCHK7;
		stu_UsbDeviceArr[3].CtrlIDarr[13] = IDC_MODLE3_SOKCHK0;
		stu_UsbDeviceArr[3].CtrlIDarr[14] = IDC_MODLE3_SOKCHK1;
		stu_UsbDeviceArr[3].CtrlIDarr[15] = IDC_MODLE3_SOKCHK2;
		stu_UsbDeviceArr[3].CtrlIDarr[16] = IDC_MODLE3_SOKCHK3;

		//8个STATIC颜色
		stu_UsbDeviceArr[4].CtrlIDarr[1] = IDC_MODULE4_ICO4;
		stu_UsbDeviceArr[4].CtrlIDarr[2] = IDC_MODULE4_ICO5;
		stu_UsbDeviceArr[4].CtrlIDarr[3] = IDC_MODULE4_ICO6;
		stu_UsbDeviceArr[4].CtrlIDarr[4] = IDC_MODULE4_ICO7;
		stu_UsbDeviceArr[4].CtrlIDarr[5] = IDC_MODULE4_ICO0;
		stu_UsbDeviceArr[4].CtrlIDarr[6] = IDC_MODULE4_ICO1;
		stu_UsbDeviceArr[4].CtrlIDarr[7] = IDC_MODULE4_ICO2;
		stu_UsbDeviceArr[4].CtrlIDarr[8] = IDC_MODULE4_ICO3;

		//8个SOCKETCHK
		stu_UsbDeviceArr[4].CtrlIDarr[9] = IDC_MODLE4_SOKCHK4;
		stu_UsbDeviceArr[4].CtrlIDarr[10] = IDC_MODLE4_SOKCHK5;
		stu_UsbDeviceArr[4].CtrlIDarr[11] = IDC_MODLE4_SOKCHK6;
		stu_UsbDeviceArr[4].CtrlIDarr[12] = IDC_MODLE4_SOKCHK7;
		stu_UsbDeviceArr[4].CtrlIDarr[13] = IDC_MODLE4_SOKCHK0;
		stu_UsbDeviceArr[4].CtrlIDarr[14] = IDC_MODLE4_SOKCHK1;
		stu_UsbDeviceArr[4].CtrlIDarr[15] = IDC_MODLE4_SOKCHK2;
		stu_UsbDeviceArr[4].CtrlIDarr[16] = IDC_MODLE4_SOKCHK3;

		//8个STATIC颜色
		stu_UsbDeviceArr[5].CtrlIDarr[1] = IDC_MODULE5_ICO4;
		stu_UsbDeviceArr[5].CtrlIDarr[2] = IDC_MODULE5_ICO5;
		stu_UsbDeviceArr[5].CtrlIDarr[3] = IDC_MODULE5_ICO6;
		stu_UsbDeviceArr[5].CtrlIDarr[4] = IDC_MODULE5_ICO7;
		stu_UsbDeviceArr[5].CtrlIDarr[5] = IDC_MODULE5_ICO0;
		stu_UsbDeviceArr[5].CtrlIDarr[6] = IDC_MODULE5_ICO1;
		stu_UsbDeviceArr[5].CtrlIDarr[7] = IDC_MODULE5_ICO2;
		stu_UsbDeviceArr[5].CtrlIDarr[8] = IDC_MODULE5_ICO3;

		//8个SOCKETCHK
		stu_UsbDeviceArr[5].CtrlIDarr[9] =  IDC_MODLE5_SOKCHK4;
		stu_UsbDeviceArr[5].CtrlIDarr[10] = IDC_MODLE5_SOKCHK5;
		stu_UsbDeviceArr[5].CtrlIDarr[11] = IDC_MODLE5_SOKCHK6;
		stu_UsbDeviceArr[5].CtrlIDarr[12] = IDC_MODLE5_SOKCHK7;
		stu_UsbDeviceArr[5].CtrlIDarr[13] = IDC_MODLE5_SOKCHK0;
		stu_UsbDeviceArr[5].CtrlIDarr[14] = IDC_MODLE5_SOKCHK1;
		stu_UsbDeviceArr[5].CtrlIDarr[15] = IDC_MODLE5_SOKCHK2;
		stu_UsbDeviceArr[5].CtrlIDarr[16] = IDC_MODLE5_SOKCHK3;



	}
	
	//第1个必须是CHECK的ID，后面用第一个做setcheck,第二到第5必须是static
	stu_UsbDeviceArr[0].CtrlIDarr[0] = IDC_PROGCHECK0;
	//PROGRESS和GROUP
	stu_UsbDeviceArr[0].CtrlIDarr[17] = IDC_GROUPBOX0;
	stu_UsbDeviceArr[0].CtrlIDarr[18] = IDC_PROGRESS0;
	//BUTTON AUTO
	stu_UsbDeviceArr[0].CtrlIDarr[19] = IDC_MODEL0_BUTTONAUTO;
	//SN STATIC
	stu_UsbDeviceArr[0].CtrlIDarr[20] = IDC_MODEL0_STATICSN;
	//计数
	stu_UsbDeviceArr[0].CtrlIDarr[21] = IDC_MODEL0_STATICCNT;
	//BUTTON CANCEL
	stu_UsbDeviceArr[0].CtrlIDarr[22] = IDC_MODEL0_BUTTONCANCEL;
	//NEXT 8 SOCKETS chk
	stu_UsbDeviceArr[0].CtrlIDarr[23] = IDC_MODULE0_ICO8;
	stu_UsbDeviceArr[0].CtrlIDarr[24] = IDC_MODULE0_ICO9;
	stu_UsbDeviceArr[0].CtrlIDarr[25] = IDC_MODULE0_ICO10;
	stu_UsbDeviceArr[0].CtrlIDarr[26] = IDC_MODULE0_ICO11;
	stu_UsbDeviceArr[0].CtrlIDarr[27] = IDC_MODULE0_ICO12;
	stu_UsbDeviceArr[0].CtrlIDarr[28] = IDC_MODULE0_ICO13;
	stu_UsbDeviceArr[0].CtrlIDarr[29] = IDC_MODULE0_ICO14;
	stu_UsbDeviceArr[0].CtrlIDarr[30] = IDC_MODULE0_ICO15;

	//8个SOCKETCHK
	stu_UsbDeviceArr[0].CtrlIDarr[31] = IDC_MODLE0_SOKCHK8;
	stu_UsbDeviceArr[0].CtrlIDarr[32] = IDC_MODLE0_SOKCHK9;
	stu_UsbDeviceArr[0].CtrlIDarr[33] = IDC_MODLE0_SOKCHK10;
	stu_UsbDeviceArr[0].CtrlIDarr[34] = IDC_MODLE0_SOKCHK11;
	stu_UsbDeviceArr[0].CtrlIDarr[35] = IDC_MODLE0_SOKCHK12;
	stu_UsbDeviceArr[0].CtrlIDarr[36] = IDC_MODLE0_SOKCHK13;
	stu_UsbDeviceArr[0].CtrlIDarr[37] = IDC_MODLE0_SOKCHK14;
	stu_UsbDeviceArr[0].CtrlIDarr[38] = IDC_MODLE0_SOKCHK15;

	//第1个必须是CHECK的ID，后面用第一个做setcheck,第二到第5必须是static
	stu_UsbDeviceArr[1].CtrlIDarr[0] = IDC_PROGCHECK1;
	
	//PROGRESS和GROUP
	stu_UsbDeviceArr[1].CtrlIDarr[17] = IDC_GROUPBOX1;
	stu_UsbDeviceArr[1].CtrlIDarr[18] = IDC_PROGRESS1;
	//BUTTON AUTO
	stu_UsbDeviceArr[1].CtrlIDarr[19] = IDC_MODEL1_BUTTONAUTO;
	//SN STATIC
	stu_UsbDeviceArr[1].CtrlIDarr[20] = IDC_MODEL1_STATICSN;
	//计数
	stu_UsbDeviceArr[1].CtrlIDarr[21] = IDC_MODEL1_STATICCNT;
	//BUTTON CANCEL
	stu_UsbDeviceArr[1].CtrlIDarr[22] = IDC_MODEL1_BUTTONCANCEL;
	//NEXT 8 SOCKETS chk
	stu_UsbDeviceArr[1].CtrlIDarr[23] = IDC_MODULE1_ICO8;
	stu_UsbDeviceArr[1].CtrlIDarr[24] = IDC_MODULE1_ICO9;
	stu_UsbDeviceArr[1].CtrlIDarr[25] = IDC_MODULE1_ICO10;
	stu_UsbDeviceArr[1].CtrlIDarr[26] = IDC_MODULE1_ICO11;
	stu_UsbDeviceArr[1].CtrlIDarr[27] = IDC_MODULE1_ICO12;
	stu_UsbDeviceArr[1].CtrlIDarr[28] = IDC_MODULE1_ICO13;
	stu_UsbDeviceArr[1].CtrlIDarr[29] = IDC_MODULE1_ICO14;
	stu_UsbDeviceArr[1].CtrlIDarr[30] = IDC_MODULE1_ICO15;

	//8个SOCKETCHK
	stu_UsbDeviceArr[1].CtrlIDarr[31] = IDC_MODLE1_SOKCHK8;
	stu_UsbDeviceArr[1].CtrlIDarr[32] = IDC_MODLE1_SOKCHK9;
	stu_UsbDeviceArr[1].CtrlIDarr[33] = IDC_MODLE1_SOKCHK10;
	stu_UsbDeviceArr[1].CtrlIDarr[34] = IDC_MODLE1_SOKCHK11;
	stu_UsbDeviceArr[1].CtrlIDarr[35] = IDC_MODLE1_SOKCHK12;
	stu_UsbDeviceArr[1].CtrlIDarr[36] = IDC_MODLE1_SOKCHK13;
	stu_UsbDeviceArr[1].CtrlIDarr[37] = IDC_MODLE1_SOKCHK14;
	stu_UsbDeviceArr[1].CtrlIDarr[38] = IDC_MODLE1_SOKCHK15;

	stu_UsbDeviceArr[2].CtrlIDarr[0] = IDC_PROGCHECK2;
	
	//PROGRESS和GROUP
	stu_UsbDeviceArr[2].CtrlIDarr[17] = IDC_GROUPBOX2;
	stu_UsbDeviceArr[2].CtrlIDarr[18] = IDC_PROGRESS2;
	//BUTTON AUTO
	stu_UsbDeviceArr[2].CtrlIDarr[19] = IDC_MODEL2_BUTTONAUTO;
	//SN STATIC
	stu_UsbDeviceArr[2].CtrlIDarr[20] = IDC_MODEL2_STATICSN;
	//计数
	stu_UsbDeviceArr[2].CtrlIDarr[21] = IDC_MODEL2_STATICCNT;
	//BUTTON CANCEL
	stu_UsbDeviceArr[2].CtrlIDarr[22] = IDC_MODEL2_BUTTONCANCEL;
	//NEXT 8 SOCKETS chk
	stu_UsbDeviceArr[2].CtrlIDarr[23] = IDC_MODULE2_ICO8;
	stu_UsbDeviceArr[2].CtrlIDarr[24] = IDC_MODULE2_ICO9;
	stu_UsbDeviceArr[2].CtrlIDarr[25] = IDC_MODULE2_ICO10;
	stu_UsbDeviceArr[2].CtrlIDarr[26] = IDC_MODULE2_ICO11;
	stu_UsbDeviceArr[2].CtrlIDarr[27] = IDC_MODULE2_ICO12;
	stu_UsbDeviceArr[2].CtrlIDarr[28] = IDC_MODULE2_ICO13;
	stu_UsbDeviceArr[2].CtrlIDarr[29] = IDC_MODULE2_ICO14;
	stu_UsbDeviceArr[2].CtrlIDarr[30] = IDC_MODULE2_ICO15;

	//8个SOCKETCHK
	stu_UsbDeviceArr[2].CtrlIDarr[31] = IDC_MODLE2_SOKCHK8;
	stu_UsbDeviceArr[2].CtrlIDarr[32] = IDC_MODLE2_SOKCHK9;
	stu_UsbDeviceArr[2].CtrlIDarr[33] = IDC_MODLE2_SOKCHK10;
	stu_UsbDeviceArr[2].CtrlIDarr[34] = IDC_MODLE2_SOKCHK11;
	stu_UsbDeviceArr[2].CtrlIDarr[35] = IDC_MODLE2_SOKCHK12;
	stu_UsbDeviceArr[2].CtrlIDarr[36] = IDC_MODLE2_SOKCHK13;
	stu_UsbDeviceArr[2].CtrlIDarr[37] = IDC_MODLE2_SOKCHK14;
	stu_UsbDeviceArr[2].CtrlIDarr[38] = IDC_MODLE2_SOKCHK15;


	stu_UsbDeviceArr[3].CtrlIDarr[0] = IDC_PROGCHECK3;
	
	//PROGRESS和GROUP
	stu_UsbDeviceArr[3].CtrlIDarr[17] = IDC_GROUPBOX3;
	stu_UsbDeviceArr[3].CtrlIDarr[18] = IDC_PROGRESS3;
	//BUTTON AUTO
	stu_UsbDeviceArr[3].CtrlIDarr[19] = IDC_MODEL3_BUTTONAUTO;
	//SN STATIC
	stu_UsbDeviceArr[3].CtrlIDarr[20] = IDC_MODEL3_STATICSN;
	//计数
	stu_UsbDeviceArr[3].CtrlIDarr[21] = IDC_MODEL3_STATICCNT;
	//BUTTON CANCEL
	stu_UsbDeviceArr[3].CtrlIDarr[22] = IDC_MODEL3_BUTTONCANCEL;
	stu_UsbDeviceArr[3].CtrlIDarr[23] = IDC_MODULE3_ICO8;
	stu_UsbDeviceArr[3].CtrlIDarr[24] = IDC_MODULE3_ICO9;
	stu_UsbDeviceArr[3].CtrlIDarr[25] = IDC_MODULE3_ICO10;
	stu_UsbDeviceArr[3].CtrlIDarr[26] = IDC_MODULE3_ICO11;
	stu_UsbDeviceArr[3].CtrlIDarr[27] = IDC_MODULE3_ICO12;
	stu_UsbDeviceArr[3].CtrlIDarr[28] = IDC_MODULE3_ICO13;
	stu_UsbDeviceArr[3].CtrlIDarr[29] = IDC_MODULE3_ICO14;
	stu_UsbDeviceArr[3].CtrlIDarr[30] = IDC_MODULE3_ICO15;

	//8个SOCKETCHK
	stu_UsbDeviceArr[3].CtrlIDarr[31] = IDC_MODLE3_SOKCHK8;
	stu_UsbDeviceArr[3].CtrlIDarr[32] = IDC_MODLE3_SOKCHK9;
	stu_UsbDeviceArr[3].CtrlIDarr[33] = IDC_MODLE3_SOKCHK10;
	stu_UsbDeviceArr[3].CtrlIDarr[34] = IDC_MODLE3_SOKCHK11;
	stu_UsbDeviceArr[3].CtrlIDarr[35] = IDC_MODLE3_SOKCHK12;
	stu_UsbDeviceArr[3].CtrlIDarr[36] = IDC_MODLE3_SOKCHK13;
	stu_UsbDeviceArr[3].CtrlIDarr[37] = IDC_MODLE3_SOKCHK14;
	stu_UsbDeviceArr[3].CtrlIDarr[38] = IDC_MODLE3_SOKCHK15;

	stu_UsbDeviceArr[4].CtrlIDarr[0] = IDC_PROGCHECK4;
	

	//PROGRESS和GROUP
	stu_UsbDeviceArr[4].CtrlIDarr[17] = IDC_GROUPBOX4;
	stu_UsbDeviceArr[4].CtrlIDarr[18] = IDC_PROGRESS4;
	//BUTTON AUTO
	stu_UsbDeviceArr[4].CtrlIDarr[19] = IDC_MODEL4_BUTTONAUTO;
	//SN STATIC
	stu_UsbDeviceArr[4].CtrlIDarr[20] = IDC_MODEL4_STATICSN;
	//计数
	stu_UsbDeviceArr[4].CtrlIDarr[21] = IDC_MODEL4_STATICCNT;
	//BUTTON CANCEL
	stu_UsbDeviceArr[4].CtrlIDarr[22] = IDC_MODEL4_BUTTONCANCEL;
	//NEXT 8 SOCKETS chk
	stu_UsbDeviceArr[4].CtrlIDarr[23] = IDC_MODULE4_ICO8;
	stu_UsbDeviceArr[4].CtrlIDarr[24] = IDC_MODULE4_ICO9;
	stu_UsbDeviceArr[4].CtrlIDarr[25] = IDC_MODULE4_ICO10;
	stu_UsbDeviceArr[4].CtrlIDarr[26] = IDC_MODULE4_ICO11;
	stu_UsbDeviceArr[4].CtrlIDarr[27] = IDC_MODULE4_ICO12;
	stu_UsbDeviceArr[4].CtrlIDarr[28] = IDC_MODULE4_ICO13;
	stu_UsbDeviceArr[4].CtrlIDarr[29] = IDC_MODULE4_ICO14;
	stu_UsbDeviceArr[4].CtrlIDarr[30] = IDC_MODULE4_ICO15;

	//8个SOCKETCHK
	stu_UsbDeviceArr[4].CtrlIDarr[31] = IDC_MODLE4_SOKCHK8;
	stu_UsbDeviceArr[4].CtrlIDarr[32] = IDC_MODLE4_SOKCHK9;
	stu_UsbDeviceArr[4].CtrlIDarr[33] = IDC_MODLE4_SOKCHK10;
	stu_UsbDeviceArr[4].CtrlIDarr[34] = IDC_MODLE4_SOKCHK11;
	stu_UsbDeviceArr[4].CtrlIDarr[35] = IDC_MODLE4_SOKCHK12;
	stu_UsbDeviceArr[4].CtrlIDarr[36] = IDC_MODLE4_SOKCHK13;
	stu_UsbDeviceArr[4].CtrlIDarr[37] = IDC_MODLE4_SOKCHK14;
	stu_UsbDeviceArr[4].CtrlIDarr[38] = IDC_MODLE4_SOKCHK15;


	stu_UsbDeviceArr[5].CtrlIDarr[0] = IDC_PROGCHECK5;
	

	//PROGRESS和GROUP
	stu_UsbDeviceArr[5].CtrlIDarr[17] = IDC_GROUPBOX5;
	stu_UsbDeviceArr[5].CtrlIDarr[18] = IDC_PROGRESS5;
	//BUTTON AUTO
	stu_UsbDeviceArr[5].CtrlIDarr[19] = IDC_MODEL5_BUTTONAUTO;
	//SN STATIC
	stu_UsbDeviceArr[5].CtrlIDarr[20] = IDC_MODEL5_STATICSN;
	//计数
	stu_UsbDeviceArr[5].CtrlIDarr[21] = IDC_MODEL5_STATICCNT;
	//BUTTON CANCEL
	stu_UsbDeviceArr[5].CtrlIDarr[22] = IDC_MODEL5_BUTTONCANCEL;
	//NEXT 8 SOCKETS chk
	stu_UsbDeviceArr[5].CtrlIDarr[23] = IDC_MODULE5_ICO8;
	stu_UsbDeviceArr[5].CtrlIDarr[24] = IDC_MODULE5_ICO9;
	stu_UsbDeviceArr[5].CtrlIDarr[25] = IDC_MODULE5_ICO10;
	stu_UsbDeviceArr[5].CtrlIDarr[26] = IDC_MODULE5_ICO11;
	stu_UsbDeviceArr[5].CtrlIDarr[27] = IDC_MODULE5_ICO12;
	stu_UsbDeviceArr[5].CtrlIDarr[28] = IDC_MODULE5_ICO13;
	stu_UsbDeviceArr[5].CtrlIDarr[29] = IDC_MODULE5_ICO14;
	stu_UsbDeviceArr[5].CtrlIDarr[30] = IDC_MODULE5_ICO15;

	//8个SOCKETCHK
	stu_UsbDeviceArr[5].CtrlIDarr[31] = IDC_MODLE5_SOKCHK8;
	stu_UsbDeviceArr[5].CtrlIDarr[32] = IDC_MODLE5_SOKCHK9;
	stu_UsbDeviceArr[5].CtrlIDarr[33] = IDC_MODLE5_SOKCHK10;
	stu_UsbDeviceArr[5].CtrlIDarr[34] = IDC_MODLE5_SOKCHK11;
	stu_UsbDeviceArr[5].CtrlIDarr[35] = IDC_MODLE5_SOKCHK12;
	stu_UsbDeviceArr[5].CtrlIDarr[36] = IDC_MODLE5_SOKCHK13;
	stu_UsbDeviceArr[5].CtrlIDarr[37] = IDC_MODLE5_SOKCHK14;
	stu_UsbDeviceArr[5].CtrlIDarr[38] = IDC_MODLE5_SOKCHK15;


	stu_UsbDeviceArr[6].CtrlIDarr[0] = IDC_PROGCHECK6;

	//PROGRESS和GROUP
	stu_UsbDeviceArr[6].CtrlIDarr[17] = IDC_GROUPBOX6;
	stu_UsbDeviceArr[6].CtrlIDarr[18] = IDC_PROGRESS6;
	//BUTTON AUTO
	stu_UsbDeviceArr[6].CtrlIDarr[19] = IDC_MODEL6_BUTTONAUTO;
	//SN STATIC
	stu_UsbDeviceArr[6].CtrlIDarr[20] = IDC_MODEL6_STATICSN;
	//计数
	stu_UsbDeviceArr[6].CtrlIDarr[21] = IDC_MODEL6_STATICCNT;
	//BUTTON CANCEL
	stu_UsbDeviceArr[6].CtrlIDarr[22] = IDC_MODEL6_BUTTONCANCEL;
	//NEXT 8 SOCKETS chk
	stu_UsbDeviceArr[6].CtrlIDarr[23] = IDC_MODULE6_ICO8;
	stu_UsbDeviceArr[6].CtrlIDarr[24] = IDC_MODULE6_ICO9;
	stu_UsbDeviceArr[6].CtrlIDarr[25] = IDC_MODULE6_ICO10;
	stu_UsbDeviceArr[6].CtrlIDarr[26] = IDC_MODULE6_ICO11;
	stu_UsbDeviceArr[6].CtrlIDarr[27] = IDC_MODULE6_ICO12;
	stu_UsbDeviceArr[6].CtrlIDarr[28] = IDC_MODULE6_ICO13;
	stu_UsbDeviceArr[6].CtrlIDarr[29] = IDC_MODULE6_ICO14;
	stu_UsbDeviceArr[6].CtrlIDarr[30] = IDC_MODULE6_ICO15;

	//8个SOCKETCHK
	stu_UsbDeviceArr[6].CtrlIDarr[31] = IDC_MODLE6_SOKCHK8;
	stu_UsbDeviceArr[6].CtrlIDarr[32] = IDC_MODLE6_SOKCHK9;
	stu_UsbDeviceArr[6].CtrlIDarr[33] = IDC_MODLE6_SOKCHK10;
	stu_UsbDeviceArr[6].CtrlIDarr[34] = IDC_MODLE6_SOKCHK11;
	stu_UsbDeviceArr[6].CtrlIDarr[35] = IDC_MODLE6_SOKCHK12;
	stu_UsbDeviceArr[6].CtrlIDarr[36] = IDC_MODLE6_SOKCHK13;
	stu_UsbDeviceArr[6].CtrlIDarr[37] = IDC_MODLE6_SOKCHK14;
	stu_UsbDeviceArr[6].CtrlIDarr[38] = IDC_MODLE6_SOKCHK15;



	//PROGRESS和GROUP
	stu_UsbDeviceArr[7].CtrlIDarr[17] = IDC_GROUPBOX7;
	stu_UsbDeviceArr[7].CtrlIDarr[18] = IDC_PROGRESS7;
	//BUTTON AUTO
	stu_UsbDeviceArr[7].CtrlIDarr[19] = IDC_MODEL7_BUTTONAUTO;
	//SN STATIC
	stu_UsbDeviceArr[7].CtrlIDarr[20] = IDC_MODEL7_STATICSN;
	//计数
	stu_UsbDeviceArr[7].CtrlIDarr[21] = IDC_MODEL7_STATICCNT;
	//BUTTON CANCEL
	stu_UsbDeviceArr[7].CtrlIDarr[22] = IDC_MODEL7_BUTTONCANCEL;
	//NEXT 8 SOCKETS chk
	stu_UsbDeviceArr[7].CtrlIDarr[23] = IDC_MODULE7_ICO8;
	stu_UsbDeviceArr[7].CtrlIDarr[24] = IDC_MODULE7_ICO9;
	stu_UsbDeviceArr[7].CtrlIDarr[25] = IDC_MODULE7_ICO10;
	stu_UsbDeviceArr[7].CtrlIDarr[26] = IDC_MODULE7_ICO11;
	stu_UsbDeviceArr[7].CtrlIDarr[27] = IDC_MODULE7_ICO12;
	stu_UsbDeviceArr[7].CtrlIDarr[28] = IDC_MODULE7_ICO13;
	stu_UsbDeviceArr[7].CtrlIDarr[29] = IDC_MODULE7_ICO14;
	stu_UsbDeviceArr[7].CtrlIDarr[30] = IDC_MODULE7_ICO15;

	//8个SOCKETCHK
	stu_UsbDeviceArr[7].CtrlIDarr[31] = IDC_MODLE7_SOKCHK8;
	stu_UsbDeviceArr[7].CtrlIDarr[32] = IDC_MODLE7_SOKCHK9;
	stu_UsbDeviceArr[7].CtrlIDarr[33] = IDC_MODLE7_SOKCHK10;
	stu_UsbDeviceArr[7].CtrlIDarr[34] = IDC_MODLE7_SOKCHK11;
	stu_UsbDeviceArr[7].CtrlIDarr[35] = IDC_MODLE7_SOKCHK12;
	stu_UsbDeviceArr[7].CtrlIDarr[36] = IDC_MODLE7_SOKCHK13;
	stu_UsbDeviceArr[7].CtrlIDarr[37] = IDC_MODLE7_SOKCHK14;
	stu_UsbDeviceArr[7].CtrlIDarr[38] = IDC_MODLE7_SOKCHK15;
	stu_UsbDeviceArr[7].CtrlIDarr[0] = IDC_PROGCHECK7;
	if (PROGRAMERMAXNUM > 8)
	{
		//PROGRESS和GROUP
		stu_UsbDeviceArr[8].CtrlIDarr[17] = IDC_GROUPBOX8;
		stu_UsbDeviceArr[8].CtrlIDarr[18] = IDC_PROGRESS8;
		//BUTTON AUTO
		stu_UsbDeviceArr[8].CtrlIDarr[19] = IDC_MODEL8_BUTTONAUTO;
		//SN STATIC
		stu_UsbDeviceArr[8].CtrlIDarr[20] = IDC_MODEL8_STATICSN;
		//计数
		stu_UsbDeviceArr[8].CtrlIDarr[21] = IDC_MODEL8_STATICCNT;
		//BUTTON CANCEL
		stu_UsbDeviceArr[8].CtrlIDarr[22] = IDC_MODEL8_BUTTONCANCEL;
		//NEXT 8 SOCKETS chk
		stu_UsbDeviceArr[8].CtrlIDarr[23] = IDC_MODULE8_ICO8;
		stu_UsbDeviceArr[8].CtrlIDarr[24] = IDC_MODULE8_ICO9;
		stu_UsbDeviceArr[8].CtrlIDarr[25] = IDC_MODULE8_ICO10;
		stu_UsbDeviceArr[8].CtrlIDarr[26] = IDC_MODULE8_ICO11;
		stu_UsbDeviceArr[8].CtrlIDarr[27] = IDC_MODULE8_ICO12;
		stu_UsbDeviceArr[8].CtrlIDarr[28] = IDC_MODULE8_ICO13;
		stu_UsbDeviceArr[8].CtrlIDarr[29] = IDC_MODULE8_ICO14;
		stu_UsbDeviceArr[8].CtrlIDarr[30] = IDC_MODULE8_ICO15;

		//8个SOCKETCHK
		stu_UsbDeviceArr[8].CtrlIDarr[31] = IDC_MODLE8_SOKCHK8;
		stu_UsbDeviceArr[8].CtrlIDarr[32] = IDC_MODLE8_SOKCHK9;
		stu_UsbDeviceArr[8].CtrlIDarr[33] = IDC_MODLE8_SOKCHK10;
		stu_UsbDeviceArr[8].CtrlIDarr[34] = IDC_MODLE8_SOKCHK11;
		stu_UsbDeviceArr[8].CtrlIDarr[35] = IDC_MODLE8_SOKCHK12;
		stu_UsbDeviceArr[8].CtrlIDarr[36] = IDC_MODLE8_SOKCHK13;
		stu_UsbDeviceArr[8].CtrlIDarr[37] = IDC_MODLE8_SOKCHK14;
		stu_UsbDeviceArr[8].CtrlIDarr[38] = IDC_MODLE8_SOKCHK15;
		stu_UsbDeviceArr[8].CtrlIDarr[0] = IDC_PROGCHECK8;

		//PROGRESS和GROUP
		stu_UsbDeviceArr[9].CtrlIDarr[17] = IDC_GROUPBOX9;
		stu_UsbDeviceArr[9].CtrlIDarr[18] = IDC_PROGRESS9;
		//BUTTON AUTO
		stu_UsbDeviceArr[9].CtrlIDarr[19] = IDC_MODEL9_BUTTONAUTO;
		//SN STATIC
		stu_UsbDeviceArr[9].CtrlIDarr[20] = IDC_MODEL9_STATICSN;
		//计数
		stu_UsbDeviceArr[9].CtrlIDarr[21] = IDC_MODEL9_STATICCNT;
		//BUTTON CANCEL
		stu_UsbDeviceArr[9].CtrlIDarr[22] = IDC_MODEL9_BUTTONCANCEL;
		//NEXT 9 SOCKETS chk
		stu_UsbDeviceArr[9].CtrlIDarr[23] = IDC_MODULE9_ICO8;
		stu_UsbDeviceArr[9].CtrlIDarr[24] = IDC_MODULE9_ICO9;
		stu_UsbDeviceArr[9].CtrlIDarr[25] = IDC_MODULE9_ICO10;
		stu_UsbDeviceArr[9].CtrlIDarr[26] = IDC_MODULE9_ICO11;
		stu_UsbDeviceArr[9].CtrlIDarr[27] = IDC_MODULE9_ICO12;
		stu_UsbDeviceArr[9].CtrlIDarr[28] = IDC_MODULE9_ICO13;
		stu_UsbDeviceArr[9].CtrlIDarr[29] = IDC_MODULE9_ICO14;
		stu_UsbDeviceArr[9].CtrlIDarr[30] = IDC_MODULE9_ICO15;

		//9个SOCKETCHK
		stu_UsbDeviceArr[9].CtrlIDarr[31] = IDC_MODLE9_SOKCHK8;
		stu_UsbDeviceArr[9].CtrlIDarr[32] = IDC_MODLE9_SOKCHK9;
		stu_UsbDeviceArr[9].CtrlIDarr[33] = IDC_MODLE9_SOKCHK10;
		stu_UsbDeviceArr[9].CtrlIDarr[34] = IDC_MODLE9_SOKCHK11;
		stu_UsbDeviceArr[9].CtrlIDarr[35] = IDC_MODLE9_SOKCHK12;
		stu_UsbDeviceArr[9].CtrlIDarr[36] = IDC_MODLE9_SOKCHK13;
		stu_UsbDeviceArr[9].CtrlIDarr[37] = IDC_MODLE9_SOKCHK14;
		stu_UsbDeviceArr[9].CtrlIDarr[38] = IDC_MODLE9_SOKCHK15;
		stu_UsbDeviceArr[9].CtrlIDarr[0] = IDC_PROGCHECK9;
	}
	
}
void CMainFrame::DispGeneralSetting()
{
	TCHAR wszTmp[200], wszTmp1[200];
	int i;
	pFormView3->RichEditShowAll(0,STR_GENERALSETTINGSEPRATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
	for (i = 0; i < sizeof(m_szVCC) / sizeof(m_szVCC[0]); i++)
	{
		
		CharToTchar(wszTmp1, m_szVCC[i]);
		wsprintf(wszTmp, L"VCC%d=%s", i, wszTmp1);
		pFormView3->RichEditShowAll(0,wszTmp, COLOR_GHOSTWHITE, CFE_BOLD, 0);
	}
	for (i = 0; i < sizeof(m_szVIO) / sizeof(m_szVIO[0]); i++)
	{

		CharToTchar(wszTmp1, m_szVIO[i]);
		wsprintf(wszTmp, L"VIO%d=%s", i, wszTmp1);
		pFormView3->RichEditShowAll(0,wszTmp, COLOR_GHOSTWHITE, CFE_BOLD, 0);
	}
	
	wsprintf(wszTmp, L"NeedIDCheck=%d", g_nIsNeedChkId);
	wsprintf(wszTmp, L"NeedPinChk=%d", g_nIsNeedPinChk);
	pFormView3->RichEditShowAll(0,wszTmp,COLOR_GHOSTWHITE, CFE_BOLD, 0);
	wsprintf(wszTmp, L"EraseWhenNotBlank=%d", g_nEraseWhenNOTBlank);
	pFormView3->RichEditShowAll(0,wszTmp, COLOR_GHOSTWHITE, CFE_BOLD, 0);
	wsprintf(wszTmp, L"AutoSense=%d", nAutoSenseAutoRun);
	pFormView3->RichEditShowAll(0,wszTmp, COLOR_GHOSTWHITE, CFE_BOLD, 0);

	pFormView3->RichEditShowAll(0,STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
	
}
void CMainFrame::DisplaySocketInfo(unsigned  wSocketMask)
{
	CString strTmp;
	int i;
	int nSocketmax=SOCKETMAX;
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))nSocketmax = 2 * SOCKETMAX;
	for (i = 0; i < nSocketmax; i++)
	{
		if (wSocketMask&(1 << i))
		{
			strTmp.Format(L"Socket %d enable",  i + 1);
		}
		else
		{
			strTmp.Format(L"Socket %d disable",  i + 1);
		}
			pFormView3->RichEditShowAll(0,strTmp, COLOR_GHOSTWHITE, 0, 0);
	}
	pFormView3->RichEditShowAll(0,STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
}
void CMainFrame::DisplayBufInfo()
{
	int nItemCnt = pFormView2->m_FileListCtrl.GetItemCount();
	int i;
	CString strTmp;
	pFormView3->RichEditShow(0, STR_BUFINFOSEPRATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
	for (i = 0; i < nItemCnt; i++)
	{
	
		strTmp = pFormView2->m_FileListCtrl.GetItemText(i, 0);
		if (strTmp == L"")break;
		int llll = strTmp.GetLength();
		strTmp += L",";
		strTmp += pFormView2->m_FileListCtrl.GetItemText(i, 1);
	
		strTmp += L",";
		strTmp += pFormView2->m_FileListCtrl.GetItemText(i, 2);
	//	m_strInfo += pFormView2->m_FileListCtrl.GetItemText(i, 2);
	//	m_strInfo += L"\r\n";
		strTmp += L",";
		strTmp += pFormView2->m_FileListCtrl.GetItemText(i, 3);
	//	m_strInfo += pFormView2->m_FileListCtrl.GetItemText(i, 3);
	//	m_strInfo += L"\r\n";
	
	
	
		pFormView3->RichEditShowAll(0,strTmp, COLOR_GHOSTWHITE, CFE_BOLD, 0);
	}

	//m_strInfo += L"\r\n";

	pFormView3->RichEditShowAll(0,STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
}

void CMainFrame::DispConfigWord(int nIsShowSep)
{
	CString strTmp;
	int i,j;
	//singelInt
	if (nIsShowSep)pFormView3->RichEditShowAll(0,STR_CONFIGINFOSEPRATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
	if (pConfigEditOneValue)
	{
		for (i = 0; i < nSingleIntCnt; i++)
		{
			strTmp.Format(L"%s Value=0x%x", pConfigEditOneValue[i].chName, pConfigEditOneValue[i].nValue);
			pFormView3->RichEditShowAll(0,strTmp, COLOR_GHOSTWHITE, CFE_BOLD, 0);
		}
	}
	if (pConfigBitMultiValue)
	{
		for (i = 0; i < nMultiCnt; i++)
		{
			//type:0复选框,2新复选框
			if ((0 == pConfigBitMultiValue[i].cType)||(2 == pConfigBitMultiValue[i].cType))
			{
				for (j = 0; j < 16; j++)
				{
					if (wcslen(pConfigBitMultiValue[i].chSubName[j]))
					{
						if (pConfigBitMultiValue[i].chSubName[j], pConfigBitMultiValue[i].nValue & (1 << j))
						{
							strTmp.Format(L"%s Multi Selector=0x%x", pConfigBitMultiValue[i].chSubName[j],1);
						}
						else
						{
							strTmp.Format(L"%s Multi Selector=0x%x", pConfigBitMultiValue[i].chSubName[j], 0);
						}
						//strTmp.Format(L"%s=0x%x", pConfigBitMultiValue[i].chSubName[j], pConfigBitMultiValue[i].nValue&(1<<j));
						pFormView3->RichEditShowAll(0,strTmp, COLOR_GHOSTWHITE, CFE_BOLD, 0);
					}
				}
				
			}
			else
			{
				strTmp.Format(L"%s Single Selector=0x%x", pConfigBitMultiValue[i].chName, pConfigBitMultiValue[i].nValue);
				pFormView3->RichEditShowAll(0,strTmp, COLOR_GHOSTWHITE, CFE_BOLD, 0);
			}		
		}
	}
	if (nIsShowSep)pFormView3->RichEditShowAll(0,STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
}
void CMainFrame::DispAutoSeq()
{
	TCHAR wsztemp[2048];
	int i;
	pFormView3->RichEditShowAll(0, STR_AUTOINFOSEPRATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
	wcscpy_s(wsztemp, L"AUTO:");
	for (i = 0; i < stu_AutoSeqGlob.nAutoCnt; i++)
	{
		if (i)wcscat(wsztemp, L"->");
		CharToTchar(wsztemp + wcslen(wsztemp), stu_FuncList.szFunListArr[stu_AutoSeqGlob.nAutoidxArray[i]]);

	}
	pFormView3->RichEditShowAll(0, wsztemp, COLOR_GHOSTWHITE, CFE_BOLD, 0);
	pFormView3->RichEditShowAll(0, STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
}
//IDX 第几组序列号，最多10组，sncnt.获取该组的几个序列号
//nprog:第几个烧录器。idx: 第几组序列。nOfset:数据偏移。sncnt:一次去几个序列号
int CMainFrame::GetOneUserSn(int nProg, int idx, int nOfset, int nNeedDelKey, int sncnt)
{
	HANDLE hFile;
	WIN32_FIND_DATA fileinfo;
	DWORD errorcode = 0;
	int i=0,j,k;
	int ret = 0, nIsFindInAnotherProg = 0, nIsFindInPrevious = 0;
	TCHAR swtmp[MAX_PATH], swtmp1[MAX_PATH];
	CString strtmp;
	CFile fs;
	CString sss;
	stu_UserSNProg[nProg][idx].nSnNum = 0;
	if (nProg==0)
		CharToTchar(swtmp, stu_GenSetting.szPath[idx]);
	else
		CharToTchar1(swtmp, stu_GenSetting.szPath[idx]);
	wcscpy(swtmp1, swtmp);
	wcscat(swtmp1, L"\\*.*");
	hFile = FindFirstFile(swtmp1, &fileinfo);

	
	TCHAR drive[_MAX_DRIVE];
	TCHAR dir[_MAX_DIR];
	TCHAR fname[_MAX_FNAME];
	TCHAR ext[_MAX_EXT];
	int meetAnotherProgcnt = 0;
	int meetPreviousCnt = 0;
	while (hFile != INVALID_HANDLE_VALUE&&errorcode != ERROR_NO_MORE_FILES)
	{
		//文件夹忽略
		if (fileinfo.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
		{
			FindNextFile(hFile, &fileinfo);
			errorcode = GetLastError();
			sss.Format(L"get empty dir %d", errorcode);
			pFormView3->RichEditShow(nProg, sss, COLOR_YELLOW, 0, 0);
			continue;
		}
		//隐藏文件
		else if (fileinfo.dwFileAttributes == FILE_ATTRIBUTE_HIDDEN)
		{
			FindNextFile(hFile, &fileinfo);
			errorcode = GetLastError();
			sss.Format(L"get hide file %d", errorcode);
		//	pFormView3->RichEditShow(nProg, sss, COLOR_RED, 0, 0);
			continue;
		}
		else if ((0 == wcscmp(L".", fileinfo.cFileName)) || (0 == wcscmp(L"..", fileinfo.cFileName)))
		{
			FindNextFile(hFile, &fileinfo);
			errorcode = GetLastError();
			continue;
		}

		wcscpy(swtmp1, swtmp);
		wcscat(swtmp1, L"\\");
		wcscat(swtmp1, fileinfo.cFileName);
		
		//if (0 == wcscmp(drive, swtmp1))
		{
		//	FindClose(hFile);
		//		return ret;
		}
		//两次取得文件名一样，说明没文件
		//wcscpy(drive, swtmp1);
		nIsFindInAnotherProg = 0;
		CString sss;
		//其他编程器已经获得该KEY
		for (j = 0; j < PROGRAMERMAXNUM; j++)
		{
			//其他的编程器取到KEY的文件不能再取
			if (j != nProg)
			{
				//8个socket，8个key
				for (k = 0; k < 8; k++)
				{
					//其他编程器已经取了
					if (0 == wcscmp(stu_UserSNProg[j][idx].swzSnUsedFile[k], swtmp1))
					{
						
						sss.Format(L"prog now %d meet prog %d", nProg, j);
						pFormView3->RichEditShow(nProg, sss, COLOR_YELLOW, 0, 0);
						meetAnotherProgcnt++;
						if (meetAnotherProgcnt > 8)
						{
						//	FindClose(hFile);
						//	return ret;
						}
						nIsFindInAnotherProg = 1;
						break;

					}
				}
					
			}	
			if (nIsFindInAnotherProg)break;
		}
		if (nIsFindInAnotherProg)
		{
			FindNextFile(hFile, &fileinfo);
			errorcode = GetLastError();
			sss.Format(L"find in another prog %d", errorcode);
			pFormView3->RichEditShow(nProg, sss, COLOR_YELLOW, 0, 0);
			continue;
		}
		for (j = 0; j < stu_UserSNProg[nProg][idx].nSnNum; j++)
		{
			if (0 == wcscmp(stu_UserSNProg[nProg][idx].swzSnUsedFile[j], swtmp1))
			{
				sss.Format(L"prog now %d meet previous %d", nProg, j);
				pFormView3->RichEditShow(nProg, sss, COLOR_RED, 0, 0);
				meetPreviousCnt ++;
				if (meetPreviousCnt > stu_UserSNProg[nProg][idx].nSnNum)
				{
				//	FindClose(hFile);
				//	return ret;
				}
				nIsFindInPrevious = 1;
				break;
			}
		}
		if (nIsFindInPrevious)
		{
			FindNextFile(hFile, &fileinfo);
			errorcode = GetLastError();
			sss.Format(L"find in previous %d", errorcode);
			pFormView3->RichEditShow(nProg, sss, COLOR_YELLOW, 0, 0);
			continue;
		}
	//	filename = fileinfo.cFileName;
			
		
		

		if (!fs.Open(swtmp1, CFile::modeRead))
		{
			wcscpy_s(swtmp, fileinfo.cFileName);
			wcscat(swtmp, L" Open fail");
			AfxMessageBox(swtmp);
			ret = -1;
			FindClose(hFile);
			break;
		}
		fs.Seek(nOfset, CFile::begin);
		//如果PTR==0,工程载入，没有分配
		if (NULL == stu_UserSNProg[nProg][idx].pSNArr)
		{
			stu_UserSNProg[nProg][idx].pSNArr = (char *)malloc(SOCKETMAX*stu_GenSetting.nUserSnLen[idx]);
			if (NULL == stu_UserSNProg[nProg][idx].pSNArr)
			{
				wsprintf(swtmp, L"Prog%d idx%d PTR==null", nProg, idx);
				AfxMessageBox(swtmp);
			}
			
		}
		if (stu_GenSetting.nUserSnLen[idx] != fs.Read(stu_UserSNProg[nProg][idx].pSNArr + i*stu_GenSetting.nUserSnLen[idx], stu_GenSetting.nUserSnLen[idx]))
		{

			wcscpy_s(swtmp, fileinfo.cFileName);
			wcscat(swtmp, L" Read Len not match");
			AfxMessageBox(swtmp);
			ret = -1;
			fs.Close();
			FindClose(hFile);
			break;
		}
		fs.Close();
		
	
	
		//移动该文件
		_wsplitpath(swtmp1, drive, dir, fname, ext);
		//删除该文件，其实就是移到根目录下
		if (stu_GenSetting.nIsDelete)
		{
			strtmp = g_wszCurPath;
		}
		else
		{
			//移到客户key目录下KPSD
			strtmp = swtmp;
			strtmp += L"\\";
		}
		strtmp += L"KPsd";

		


		DWORD dwAttr = GetFileAttributesW(strtmp);
		if (dwAttr == 0xFFFFFFFF) //文件夹不存在
		{
			sss.Format(L"loop %d", errorcode);
			pFormView3->RichEditShow(nProg, sss, COLOR_YELLOW, 0, 0);
			if (0 == CreateDirectoryW(strtmp, NULL))
			{
				AfxMessageBox(L"create kpsd fail");
			}
		}
			


		wcscpy(stu_UserSNProg[nProg][idx].swzSnUsedFile[stu_UserSNProg[nProg][idx].nSnNum], swtmp1);
		stu_UserSNProg[nProg][idx].nSnNum++;

	
		
		FindNextFile(hFile, &fileinfo);
		errorcode = GetLastError();
		sss.Format(L"loop %d", errorcode);
		pFormView3->RichEditShow(nProg, sss, COLOR_YELLOW, 0, 0);
		i++;
		//获得足够的序列号后退出
		if (i == sncnt)break;
	}
	if (errorcode == ERROR_NO_MORE_FILES)
	{
		pFormView3->RichEditShow(nProg, L"no files", COLOR_YELLOW, 0, 0);
		
	}

	FindClose(hFile);

	return ret;
}

void CMainFrame::GetUserSnFromUserPath()
{
	//GetOneUserSn(0, 0, 4);
	//GetOneUserSn(0, 1, 2);
}
CMainFrame::~CMainFrame()
{
	int i;
	/*if(NULL!=m_pAlgoData)free(m_pAlgoData);
	if(NULL!=m_pFpga0Data_320)free(m_pFpga0Data_320);
	if(NULL!=m_pFpga1Data_320)free(m_pFpga1Data_320);	
	if (NULL != m_pConfigFile)free(m_pConfigFile);*/
	for (i = 0; i < PROGRAMERMAXNUM; i++)
	{
		
		if (stu_UsbDeviceArr[i].pUsbDevice)
		{
			if (stu_UsbDeviceArr[i].pUsbDevice->IsOpen()) stu_UsbDeviceArr[i].pUsbDevice->Close();
			delete stu_UsbDeviceArr[i].pUsbDevice;
		}
	}
	
}


int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	
	if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
		| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
		!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
	{
		TRACE0("Failed to create toolbar\n");
		return -1;      // fail to create
	}
	
	
	//m_wndToolBar.SetBarStyle( CBRS_TOOLTIPS );
	
	m_wndToolBar.LoadTrueColorToolBar(32,

		IDB_FILEOPEN_NORMAL,

		IDB_FILEOPEN_NORMAL,

		IDB_FILEOPEN_DIS);
	if (!m_wndStatusBar.Create(this) ||
		!m_wndStatusBar.SetIndicators(indicators,
		  sizeof(indicators)/sizeof(UINT)))
	{
		TRACE0("Failed to create status bar\n");
		return -1;      // fail to create
	}
	UINT array[4];
	for (int i = 0; i < 4; i++)
	{
		array[i] = 100 + i;
	}

	

	m_wndStatusBar.SetPaneInfo(1, array[1], SBPS_NORMAL, 300);
	m_wndStatusBar.SetPaneText(1, g_wszCapTime);


	RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);




	// TODO: Delete these three lines if you don't want the toolbar to be dockable
	m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
	EnableDocking(CBRS_ALIGN_ANY);
	DockControlBar(&m_wndToolBar);
	
	m_wndToolBar.GetToolBarCtrl().SetExtendedStyle(TBSTYLE_EX_DRAWDDARROWS);//设置工具栏的扩展风格  
	DWORD dwStyle = m_wndToolBar.GetButtonStyle(m_wndToolBar.CommandToIndex(ID_MENU_FUN10));//获取按钮控件的风格  
	//dwStyle |= TBSTYLE_DROPDOWN;//设置下拉风格  
	//m_wndToolBar.SetButtonStyle(m_wndToolBar.CommandToIndex(ID_MENU_FUN10), dwStyle);

	if (0 == wcscmp(g_swzLanguage, L"zh_CN"))
	{
		GetMenu()->GetSubMenu(3)->CheckMenuItem(ID_LANGUAGE_CHINESE, MF_BYCOMMAND | MF_CHECKED);
		GetMenu()->GetSubMenu(3)->CheckMenuItem(ID_LANGUAGE_ENGLISH, MF_BYCOMMAND | MF_UNCHECKED);
		//SetThreadUILanguage(MAKELANGID(LANG_CHINESE_SIMPLIFIED, SUBLANG_CHINESE_SIMPLIFIED));
	}
	else if (0 == wcscmp(g_swzLanguage, L"en_US"))
	{
		GetMenu()->GetSubMenu(3)->CheckMenuItem(ID_LANGUAGE_CHINESE, MF_BYCOMMAND | MF_UNCHECKED);
		GetMenu()->GetSubMenu(3)->CheckMenuItem(ID_LANGUAGE_ENGLISH, MF_BYCOMMAND | MF_CHECKED);
	//	SetThreadUILanguage(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US));
	}
	switch (GetProgramerCount())
	{
		case 1:
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_1, MF_BYCOMMAND | MF_CHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_2, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_4, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_6, MF_BYCOMMAND | MF_UNCHECKED);
			break;
		case 2:
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_1, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_2, MF_BYCOMMAND | MF_CHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_4, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_6, MF_BYCOMMAND | MF_UNCHECKED);
			break;
		case 3:
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_1, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_2, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_4, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_6, MF_BYCOMMAND | MF_UNCHECKED);
			break;
		case 4:
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_1, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_2, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_4, MF_BYCOMMAND | MF_CHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_6, MF_BYCOMMAND | MF_UNCHECKED);
			break;
		case 5:
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_1, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_2, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_4, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_6, MF_BYCOMMAND | MF_UNCHECKED);
			break;
		case 6:
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_1, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_2, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_4, MF_BYCOMMAND | MF_UNCHECKED);
			GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_6, MF_BYCOMMAND | MF_CHECKED);
			break;
	}
	
	for (int i = 0; i < PROGRAMERMAXNUM; i++)
	{
		stu_UsbDeviceArr[i].pUsbDevice = new CCyUSBDevice(this->m_hWnd, CYUSBDRV_GUID, true);


		//必须加CLOSE，否则自动都OPEN
		stu_UsbDeviceArr[i].pUsbDevice->Close();


	}

	MruFile.InitMenuFromIni();
	SetTimer(2, 3000, NULL);
	RegisterHotKey(this->GetSafeHwnd(), 0, MOD_ALT, 's');


	
	RegisterDeviceInterface();

	CMenu *pMenu = AfxGetMainWnd()->GetMenu();		//主菜单指针
	CMenu *pFileMenu = pMenu->GetSubMenu(3);		//“帮助”菜单指针


	pFileMenu->EnableMenuItem(ID_MENU_DEVICELIST, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);


	
	return 0;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CFrameWnd::PreCreateWindow(cs) )
		return FALSE;
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	cs.dwExStyle &= ~WS_EX_CLIENTEDGE;
	cs.lpszClass = AfxRegisterWndClass(0);
	return TRUE;
}


// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CFrameWnd::Dump(dc);
}

#endif //_DEBUG


// CMainFrame message handlers


DWORD WINAPIV CMainFrame::DataAnalysis(LPVOID lParam)
{



	// TODO:  在此添加控件通知处理程序代码
	int i=0, j=0, k=0, n=0;

	//CMainFrame *pMainframe = (CMainFrame *)AfxGetApp()->m_pMainWnd;
	

	//TCHAR wszTemp[MAX_PATH];
	CString strtemp;
	CMainFrame *pThis = (CMainFrame *)lParam;
	
	CString strSource = pThis->m_strReadFileDefaultPath[0];
	int nBkTblcnt=0, MB32nBkTblCnt, nRemainTblCnt;
	LONGLONG llRemainMB;
	LONGLONG  llRemainKB;
	//	int remainB;
	CString strDes;
	int nRealFileSize = 0;

	//默认值
	int nDftValue;

	//粒度大小
	int nFitness;
	int nbarsteplen;
	int nRdLen;

	UCHAR tmp;
	CProgressWnd wndProgress;
	if (!wndProgress.Create(pThis, L"Data Analysis"))
		return -1;
	wndProgress.GoModal(); // Call this if you want a modal window

	//CMainFrame * pMainFrame = (CMainFrame *)AfxGetApp()->m_pMainWnd;
	//创建BUFFER文件
	UCHAR *pDataFill = (UCHAR *)malloc(SIZE32MB);
	CFileException e;
	CFile64 srcfd;
	
	int nidx = 0;



	///默认值
	sscanf(pstuDevInfo[g_curDeviceSel].szBufValueArrs[0], "%x", &nDftValue);
	if (nDftValue)nDftValue = 0xff;
	else nDftValue = 0;
	// 粒度
	nFitness = pstuDevInfo[g_curDeviceSel].nFitNess;
	CFileStatus status;
	CFile::GetStatus(strSource, status);

	//（文件大小减文件载入地址再加上缓冲区偏移量）大于缓冲区大小
	
	if (g_nIsEmmc )
	{


		
		pThis->pFormView3->RichEditShow(0, L"Data Analysis", COLOR_YELLOW, 0, 0);
		//文件大小是512的倍数
		if (status.m_size%nFitness)
		{
			status.m_size = (status.m_size / nFitness + 1)*nFitness;
		}

		nBkTblcnt = status.m_size / (nFitness * 8);
		if (status.m_size % (nFitness * 8))
		{
			nBkTblcnt++;
		}
		if (g_pBlktblData)free(g_pBlktblData);
		g_pBlktblData = (CHAR *)malloc(nBkTblcnt);
		memset(g_pBlktblData, 0, nBkTblcnt);
		MB32nBkTblCnt = SIZE32MB / nFitness / 8;
	}


	if (!srcfd.Open(strSource, GENERIC_READ, 0, OPEN_EXISTING, &e))
	{
		AfxMessageBox(L"Open srcfile error");
		free(pDataFill);
		return -1;
	}




	
	llRemainKB = llRemainMB = status.m_size;

	if (llRemainMB >=SIZE32MB)
	{

		llRemainKB = llRemainMB;
		nbarsteplen = llRemainMB / SIZE32MB;
		wndProgress.SetRange(0, nbarsteplen);
		for (i = 0; i < (llRemainMB / SIZE32MB); i++)
		{
			nRdLen=srcfd.Read(pDataFill, SIZE32MB);
			memset(pDataFill + nRdLen, nDftValue, SIZE32MB - nRdLen);
			wndProgress.SetPos(i);
			wndProgress.PeekAndPump();
			Sleep(1);
		
			llRemainKB -= SIZE32MB;
			nidx = 0;
	
			//EMMC fitness
			if (g_nIsEmmc )
			{
				for (n = 0; n < MB32nBkTblCnt; n++)
				{
					for (j = 0; j < 8; j++)
					{
						tmp = nDftValue;
						if (nDftValue == 0xff)
						{
							for (k = 0; k < nFitness; k++)
							{
								tmp &= pDataFill[nidx++];
								if (tmp != (UCHAR)nDftValue)
								{
									nidx += nFitness - k - 1;
									break;
								}
							}
						}
						else
						{
							for (k = 0; k < nFitness; k++)
							{
								tmp |= (pDataFill[nidx++]);
								if (tmp != (UCHAR)nDftValue)
								{
									nidx += nFitness - k - 1;
									break;
								}
							}
						}

						if (tmp != (UCHAR)nDftValue)
						{
							g_pBlktblData[i * MB32nBkTblCnt + n] |= (1 << j);
						}
					}

				}
			}
		}
	}

	//最后多出来那些不到4BM,fitness的。取数据的时候会在MAP里面补0
	if (llRemainKB)
	{
		nidx = 0;
		if (nFitness)
			nRemainTblCnt = llRemainKB / (nFitness * 8);
		//memset(pDataFill, nDftValue, SIZE32MB);
		nRdLen=srcfd.Read(pDataFill, llRemainKB);
		memset(pDataFill + nRdLen, nDftValue, SIZE32MB - nRdLen);
		
	
		if (g_nIsEmmc )
		{
			//有几个字节
			for (n = 0; n < nRemainTblCnt; n++)
			{
				for (j = 0; j < 8; j++)
				{
					tmp = nDftValue;
					if (nDftValue == 0xff)
					{
						for (k = 0; k < nFitness; k++)
						{
							tmp &= pDataFill[nidx++];
							if (tmp != (UCHAR)nDftValue)
							{
								nidx += nFitness - k - 1;
								break;
							}
						}
					}
					else
					{
						for (k = 0; k < nFitness; k++)
						{
							tmp |= (pDataFill[nidx++]);
							if (tmp != (UCHAR)nDftValue)
							{
								nidx += nFitness - k - 1;
								break;
							}
						}
					}

					if (tmp != (UCHAR)nDftValue)
					{
						g_pBlktblData[i*MB32nBkTblCnt] |= (1 << j);
					}
				}
				llRemainKB -= SIZE32MB;
			}
			//最后不到一个字节
			for (j = 0; j < llRemainKB / nFitness; j++)
			{
				tmp = nDftValue;
				if (nDftValue == 0xff)
				{
					for (k = 0; k < nFitness; k++)
					{
						tmp &= pDataFill[nidx++];
						if (tmp != (UCHAR)nDftValue)
						{
							nidx += nFitness - k - 1;
							break;
						}
					}
				}
				else
				{
					for (k = 0; k < nFitness; k++)
					{
						tmp |= (pDataFill[nidx++]);
						if (tmp != (UCHAR)nDftValue)
						{
							nidx += nFitness - k - 1;
							break;
						}
					}
				}

				if (tmp != (UCHAR)nDftValue)
				{
					g_pBlktblData[i*MB32nBkTblCnt + nRemainTblCnt] |= (1 << j);
				}
			}
		}



	}
	wndProgress.SetPos(llRemainKB / nFitness);

	free(pDataFill);
	if (nFitness)
	{
		pThis->stu_progdll.pBlkTblData = g_pBlktblData;
		pThis->stu_progdll.nTblLen = nBkTblcnt;
	}
	wndProgress.Clear();
	wndProgress.DestroyWindow();
	return 0;

}
void CMainFrame::DispSocketStatSum()
{
	int nThIdx = 0;
	CString strtmp;
	for (nThIdx = 0; nThIdx < PROGRAMERMAXNUM; nThIdx++)
	{
		//if (stu_UsbDeviceArr[nThIdx].status != USBNOTCONNECT)
		{
			if (stu_UsbDeviceArr[nThIdx].nTotalCnt)
			{
				strtmp.Format(L"Site%d  Total:%d  Success:%d  Fail:%d", m_nSiteNo[nThIdx], stu_UsbDeviceArr[nThIdx].nTotalCnt, stu_UsbDeviceArr[nThIdx].nTotalCnt - stu_UsbDeviceArr[nThIdx].nTotalFailCnt, stu_UsbDeviceArr[nThIdx].nTotalFailCnt);
				logsumStr(strtmp);
				strtmp.Format(L"Site%d  SockFail %d,%d,%d,%d,%d,%d,%d,%d", m_nSiteNo[nThIdx], stu_UsbDeviceArr[nThIdx].nSokFailCnt[0], stu_UsbDeviceArr[nThIdx].nSokFailCnt[1], stu_UsbDeviceArr[nThIdx].nSokFailCnt[2], stu_UsbDeviceArr[nThIdx].nSokFailCnt[3], \
					stu_UsbDeviceArr[nThIdx].nSokFailCnt[4], stu_UsbDeviceArr[nThIdx].nSokFailCnt[5], stu_UsbDeviceArr[nThIdx].nSokFailCnt[6], stu_UsbDeviceArr[nThIdx].nSokFailCnt[7]);
				logsumStr(strtmp);
			}
			
		}
	}

}
DWORD CMainFrame::CreateDataAnalysis()
{


//	CProgressBar bar(_T(""), 100, 100, TRUE);
//	pBbar = &bar;

	CWinThread      *pThread = AfxBeginThread((AFX_THREADPROC)DataAnalysis, (LPVOID)this);
	MSG msg;
	while (TRUE) {
		DWORD dwRet = MsgWaitForMultipleObjects(1, &pThread->m_hThread, FALSE, INFINITE, QS_ALLINPUT);
		switch (dwRet) {
		case WAIT_OBJECT_0:
			ATLTRACE(_T("等待子线程结束成功"));
			break;
		case WAIT_OBJECT_0 + 1:
			PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
			DispatchMessage(&msg);
			continue;
		default:
			break;
		}
		break;
	}
	
	return 0;

}


BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
{
	// TODO: Add your specialized code here and/or call the base class
	int i = 0;
	CRect rect;
	GetClientRect(&rect);
	//创建静态窗口

	// create splitter window
	if (!m_wndSplitter.CreateStatic(this, 1, 3))
		return FALSE;

	if (!m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CFormLeft), CSize(rect.Width() / 10, rect.Height()), pContext) ||
		!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CFormRight), CSize(rect.Width() / 10 *5, rect.Height()), pContext) ||
		!m_wndSplitter.CreateView(0, 2, RUNTIME_CLASS(CFormView3), CSize(rect.Width() / 4, rect.Height()), pContext))
	{
		m_wndSplitter.DestroyWindow();
		return FALSE;
	}
	//获得3FORMVIEW个指针
	pFormView1 = (CFormLeft *)m_wndSplitter.GetPane(0, 0);
	pFormView2 = (CFormRight *)m_wndSplitter.GetPane(0, 1);
	pFormView3 = (CFormView3 *)m_wndSplitter.GetPane(0, 2);

	//获得FORMVIEW3位置，大小
	CRect rect1;
	pFormView3->GetWindowRect(&rect1);
	ScreenToClient(&rect1);
	//RICHEDIT占满 formview3
	pFormView3->m_RichEdit0.MoveWindow(&rect1);
	//按钮尺寸
	pFormView1->GetWindowRect(&rect1);
	ScreenToClient(&rect1);
	rect1.left = 0;
	rect1.top = 0 + (rect.Height() / 10)*i;
	rect1.right = rect.Width() / 5;
	rect1.bottom = rect.Height() / 20 + (rect.Height() / 20)*i;
	for (i = 0; i < sizeof(pFormView1->m_ProcBtn)/sizeof(pFormView1->m_ProcBtn[0]); i++)
//	for (i = 0; i < 20; i++)
	{
		pFormView1->m_ProcBtn[i].SetMouseCursorHand();
		pFormView1->m_ProcBtn[i].SetTextHotColor(RGB(63, 72, 204));
	}
	

	//按钮字体
	CFont * f;
	f = new CFont;
	f->CreateFont(20, // nHeight 
		0, // nWidth 
		0, // nEscapement 
		0, // nOrientation 
		FW_BOLD, // nWeight 
		TRUE, // bItalic 
		FALSE, // bUnderline 
		0, // cStrikeOut 
		ANSI_CHARSET, // nCharSet 
		OUT_DEFAULT_PRECIS, // nOutPrecision 
		CLIP_DEFAULT_PRECIS, // nClipPrecision 
		DEFAULT_QUALITY, // nQuality 
		DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily 
		_T("Arial")); // lpszFac 
	for (i = 0; i < sizeof(pFormView1->m_ProcBtn) / sizeof(pFormView1->m_ProcBtn[0]); i++)
	{
		pFormView1->m_ProcBtn[i].SetFont(f);
	}
	
	//set the target for mapped messages
	((CFormLeft*)m_wndSplitter.GetPane(0,0))->SetTarget(m_wndSplitter.GetPane(0,1));



	m_bCreateClient = 1;
	//USB 事件
	SetTimer(1, 1000, NULL);
	//定时LOG 事件
	//SetTimer(3, 1000*20, NULL);

	//cMenuDropDown.LoadMenu(IDR_MENU1);



	return TRUE;
}



//type:0 开始
//DBT_DEVICEARRIVAL
//DBT_DEVICEREMOVECOMPLETE
bool CMainFrame::EnumerateEndpointForTheSelectedDevice(int type,CString strSN)
{
	int nDeviceIndex = 0;
	int nInsertionCount = 0;
	int nDeviceCount = 0;
	TCHAR wszSerialNum[60];
	char sn[50];
	char cIsSD;
	CString strtmp;
	
	// Is there any FX device connected to system?
	int i,j,k;
	
	
	if (stu_UsbDeviceArr[0].pUsbDevice != NULL)
	{
		
		 nDeviceCount = stu_UsbDeviceArr[0].pUsbDevice->DeviceCount();
		if (nDeviceCount > gnProgrammeronlineNum)
		{
			for (i = 0; i < nDeviceCount - gnProgrammeronlineNum; i++)
			{
				m_strDeviceData.Format(L"(0x%04X - 0x%04X) %s\n", stu_UsbDeviceArr[0].pUsbDevice->VendorID, stu_UsbDeviceArr[0].pUsbDevice->ProductID, CString(stu_UsbDeviceArr[0].pUsbDevice->FriendlyName));
			//	pFormView3->RichEditShow(i,m_strDeviceData, OPERATIONCOLOR,0,0);
			}
			
		}
		else if (nDeviceCount < gnProgrammeronlineNum)
		{
			for (i = 0; i < gnProgrammeronlineNum - nDeviceCount; i++)
			{
				m_strDeviceData.Format(L"Usb Removed");
				//pFormView3->RichEditShow(i,m_strDeviceData, OPERATIONCOLOR,0,0);
			}
		}
		gnProgrammeronlineNum = nDeviceCount;
		
		if (gnProgrammeronlineNum)g_isProgramOnline = 1;
	}

	
	
	//软件打开时USB已经连上
	if (type == 0)
	{
		
		for (i = 0; i < PROGRAMERMAXNUM; i++)
		{
			if (stu_UsbDeviceArr[i].pUsbDevice != NULL)
			{
				if (TRUE == stu_UsbDeviceArr[i].pUsbDevice->Open(i))
				{
					

					stu_UsbDeviceArr[i].status = USBCONNECT_IDLE;
					stu_UsbDeviceArr[i].nUsbOpenIdx = i;
					//m_nSlectedUSBDeviceOpen[i] = 1;
					//if (0 == strlen(stu_UsbDeviceArr[i].serialNO))
					{
						GetSN_SD(i, stu_UsbDeviceArr[i].serialNO,&cIsSD);
						/*
#ifndef ONLINE
						if (g_nProgrammerDrop[i])
						{
							stu_UsbDeviceArr[i].status = USBNOTCONNECT;
							stu_UsbDeviceArr[i].nUsbOpenIdx = 0;
							return 0;
						}
#endif
*/
						if (stu_UsbDeviceArr[i].serialNO[4] == 0x31)
						{
							stu_UsbDeviceArr[i].cIsFPGA256 = 1;
						}
						else if (stu_UsbDeviceArr[i].serialNO[4] == 0x30)
						{
							stu_UsbDeviceArr[i].cIsFPGA256 = 0;
						}
						else
						{
							stu_UsbDeviceArr[i].cIsFPGA256 = 1;
						}
						
					}
				
			
				}
			}
		}
	}
	//插入
	else if (type == DBT_DEVICEARRIVAL)
	{
		AfxMessageBox(L"抓到插入USB 消息了");

	}
	//拔除
	else if (type == DBT_DEVICEREMOVECOMPLETE)
	{
		for (i = 0; i < PROGRAMERMAXNUM; i++)
		{
			//原来是打开的
		//	if (stu_UsbDeviceArr[i].status != USBNOTCONNECT)
			{

				
				TCHAR *pSzw = strSN.GetBuffer();
				strSN.ReleaseBuffer();
				TcharToChar(sn, pSzw);
				sn[16] = 0;
					
			
				////原来是打开的
				//if (1 == stu_UsbDeviceArr[i].pUsbDevice->IsOpen())
				if (0 == strcmp(sn, stu_UsbDeviceArr[i].serialNO))
				{

					g_nProgrammerDrop[i] = 1;
					//stu_UsbDeviceArr[i].pUsbDevice->Open(stu_UsbDeviceArr[i].nUsbOpenIdx);				
					//if (0 == stu_UsbDeviceArr[i].pUsbDevice->IsOpen())
					{
						stu_UsbDeviceArr[i].pUsbDevice->Close();
						stu_UsbDeviceArr[i].status = USBNOTCONNECT;
						g_SerialResBuf[(m_nSiteNo[i] - 1)] = SER_PROG_NOTCONNECT;

//						memset(&g_SerialResBuf[32 + (m_nSiteNo[i] - 1) * 32], 0, 8);

						memset(&g_SerialResBuf[32 + (m_nSiteNo[i] - 1) * SOCKETMAX], 0, 8);
						

						stu_UsbDeviceArr[i].nUsbOpenIdx = 0xffffffff;

						memset(stu_UsbDeviceArr[i].serialNO, 0, sizeof(stu_UsbDeviceArr[i].serialNO));

						for (j = 0; j < 2*SOCKETMAX; j++)
						{
							pFormView2->mp_Static_ModArr[i][j]->SetIcon(pFormView2->hIconGrays[j]);
						}
						pFormView2->GetDlgItem(stu_UsbDeviceArr[i].CtrlIDarr[20])->SetWindowTextW(L"SN:");
						strtmp.Format(L"Programmer Disconnect\n");
						pFormView3->RichEditShow(i, strtmp,COLOR_RED, CFE_BOLD, 8);
						stu_ProgLocList.cIsActive[i] = 0;
					}
				}
			}
			
		}
		return TRUE;
	}
	STU_USBDEVICETYP DeviceTemp[PROGRAMERMAXNUM];
	//主要是拷贝控件ID
	//memcpy(DeviceTemp, stu_UsbDeviceArr, sizeof(stu_UsbDeviceArr));
	memset(DeviceTemp, 0, sizeof(DeviceTemp));

	for (i = 0; i < PROGRAMERMAXNUM; i++)
	{
		memcpy(DeviceTemp[i].CtrlIDarr, stu_UsbDeviceArr[i].CtrlIDarr, sizeof(stu_UsbDeviceArr[i].CtrlIDarr));
		//DeviceTemp[i].serialNO[0] = 0;
		//DeviceTemp[i].status = USBNOTCONNECT;
		stu_ProgLocList.cIsActive[i] = 0;
		DeviceTemp[i].cIsFPGA256 = 0;
	}
	//当前在线编程器数量
	for (i = 0; i < gnProgrammeronlineNum; i++)
	{
		//客户PROG编程器数量，从客户编程里寻找当前在线PROG应该匹配的位置
		for (j = 0; j < g_nCustomerDefProgCnt; j++)
		{
			//比较 PROGLOC.INI里面SN的12BYTES
			if ((0 == memcmp(stu_UsbDeviceArr[i].serialNO+4, stu_ProgLocList.szProgLocList[j],12))&&(0<strlen(stu_UsbDeviceArr[i].serialNO)))
			{
			
					//缓存J的数据				
				//i,j对换,其中CTRLID要保留，因为这是对应位置的空间。
				memcpy(&DeviceTemp[j].pUsbDevice, &stu_UsbDeviceArr[i].pUsbDevice, int(stu_UsbDeviceArr[i].CtrlIDarr) - int(&stu_UsbDeviceArr[i].pUsbDevice));
				memcpy(&DeviceTemp[j].nSockProgStatus, &stu_UsbDeviceArr[i].nSockProgStatus, int(stu_UsbDeviceArr[i].szSDPrjName) - int(&stu_UsbDeviceArr[i].nSockProgStatus) + sizeof(stu_UsbDeviceArr[i].szSDPrjName));
				DeviceTemp[j].cIsFPGA256 = stu_UsbDeviceArr[i].cIsFPGA256;

				CharToTchar(wszSerialNum, DeviceTemp[j].serialNO+4);

				strtmp.Format(L"SN:%s\n", wszSerialNum);
				pFormView3->RichEditShow(j, strtmp, COLOR_BLUE, 0, 0);
				
			

			
				
				for (k = 0; k < 2 * SOCKETMAX; k++)
				{
					if (stu_UsbDeviceArr[j].curSocketUnit&(1 << k))
					{
						pFormView2->mp_Static_ModArr[j][k]->SetIcon(pFormView2->hIconGreens[k]);
					}
			
						
				}
				
				strtmp.Format(L"SN:%s\n", wszSerialNum);
				
				pFormView2->GetDlgItem(stu_UsbDeviceArr[j].CtrlIDarr[20])->SetWindowTextW(strtmp);
				stu_ProgLocList.cIsActive[j] = 1;
#ifndef SNPROGRAM
				SetTimer(4+j, 2000, NULL);
#endif
				break;
			}
		}
		//遍历到最后还是没有序列号安排。从前找空位安放
		if (j == g_nCustomerDefProgCnt)
		{
			for (j = 0; j < g_nCustomerDefProgCnt; j++)
			{
				if ((0 == stu_ProgLocList.cIsActive[j]) && (0 < strlen(stu_UsbDeviceArr[i].serialNO)) && (0 == strlen(stu_ProgLocList.szProgLocList[j])))
				{
					//缓存J的数据				
					//i,j对换,其中CTRLID要保留，因为这是对应位置的空间。
					memcpy(&DeviceTemp[j].pUsbDevice, &stu_UsbDeviceArr[i].pUsbDevice, int(stu_UsbDeviceArr[i].CtrlIDarr) - int(&stu_UsbDeviceArr[i].pUsbDevice));
					memcpy(&DeviceTemp[j].nSockProgStatus, &stu_UsbDeviceArr[i].nSockProgStatus, int(stu_UsbDeviceArr[i].szSDPrjName) - int(&stu_UsbDeviceArr[i].nSockProgStatus) + sizeof(stu_UsbDeviceArr[i].szSDPrjName));
					DeviceTemp[j].cIsFPGA256 = stu_UsbDeviceArr[i].cIsFPGA256;
					CharToTchar(wszSerialNum, DeviceTemp[j].serialNO+4);
					strtmp.Format(L"SN:%s\n", wszSerialNum);
					pFormView3->RichEditShow(j, strtmp, COLOR_BLUE, 0, 0);
					
		
					for (k = 0; k < 2 * SOCKETMAX; k++)
					{
						if (stu_UsbDeviceArr[j].curSocketUnit&(1 << k))
						{
							pFormView2->mp_Static_ModArr[j][k]->SetIcon(pFormView2->hIconGreens[k]);
						}
						
					//	if (g_curDeviceSel != -1)
						{
							
						}

					}
					g_SerialResBuf[m_nSiteNo[j] - 1] = SER_PROG_READY;
					
					stu_ProgLocList.cIsActive[j] = 1;
					strtmp.Format(L"SN:%s\n", wszSerialNum);

					pFormView2->GetDlgItem(stu_UsbDeviceArr[j].CtrlIDarr[20])->SetWindowTextW(strtmp);
					stu_ProgLocList.cIsActive[j] = 1;
#ifndef SNPROGRAM
					SetTimer(4+j, 2000, NULL);
#endif
					break;
				}
			}
		}

	}
	j = 0;
	//剩余没有编程器的或者有编程器没号的。放在其他的PLANE位置
	for (i = 0; i < PROGRAMERMAXNUM; i++)
	{
			//没有序列号的放在剩余plane位置
			if (0 == strlen(stu_UsbDeviceArr[i].serialNO))
			{
				for (; j < PROGRAMERMAXNUM; j++)
				{
					if (0 == strlen(DeviceTemp[j].serialNO))
					{
						memcpy(&DeviceTemp[j].pUsbDevice, &stu_UsbDeviceArr[i].pUsbDevice, int(stu_UsbDeviceArr[i].CtrlIDarr) - int(&stu_UsbDeviceArr[i].pUsbDevice));
						memcpy(&DeviceTemp[j].nSockProgStatus, &stu_UsbDeviceArr[i].nSockProgStatus, int(stu_UsbDeviceArr[i].szSDPrjName) - int(&stu_UsbDeviceArr[i].nSockProgStatus) + sizeof(stu_UsbDeviceArr[i].szSDPrjName));
						DeviceTemp[j].cIsFPGA256 = stu_UsbDeviceArr[i].cIsFPGA256;
						j++;
						break;
					}
				}	
			}
		}
	


	memcpy(stu_UsbDeviceArr, DeviceTemp, sizeof(stu_UsbDeviceArr));
	for (i = 0; i < PROGRAMERMAXNUM; i++)
	{
		stu_UsbDeviceArr[i].curSocketUnit = g_nSocketUnit[i];
	}

	

	
	return TRUE;
}


bool CMainFrame::RegisterDeviceInterface()
{
	DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
	


	ZeroMemory(&NotificationFilter, sizeof(NotificationFilter));
	NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
	NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
	NotificationFilter.dbcc_classguid = CYUSBDRV_GUID;

	if (m_hDeviceNotify == NULL) m_hDeviceNotify = new HDEVNOTIFY;
	*m_hDeviceNotify = RegisterDeviceNotification(
		this->m_hWnd,                       // events recipient
		&NotificationFilter,        // type of device
		DEVICE_NOTIFY_WINDOW_HANDLE // type of recipient handle
		);

	if (NULL == *m_hDeviceNotify)
	{
		AfxMessageBox(TEXT("RegisterDeviceNotification"));
		delete m_hDeviceNotify;
		m_hDeviceNotify = NULL;
		return FALSE;
	}

	return TRUE;
}


LRESULT CMainFrame::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{

	DWORD UNITMASK;
	// TODO:  在此添加专用代码和/或调用基类
	// TODO:  在此添加专用代码和/或调用基类
	if (message == WM_DEVICECHANGE && wParam >= DBT_DEVICEARRIVAL)
	{
		PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;
		PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
		UNITMASK = lpdbv->dbcv_unitmask;

		
		if (wParam == DBT_DEVICEARRIVAL && lpdb->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
		{
			//SurveyExistingDevices();
			//if (this->m_pThread == NULL) EnumerateEndpointForTheSelectedDevice();
			//EnumerateEndpointForTheSelectedDevice(DBT_DEVICEARRIVAL, szDevId);
			PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)lpdb;
			ASSERT(lstrlen(pDevInf->dbcc_name) > 4);
			CString szDevId = pDevInf->dbcc_name + 4;
			int idx = szDevId.ReverseFind(_T('#'));
			ASSERT(-1 != idx);
			szDevId.Truncate(idx);

			//收到USB插入信号不再响应。掉线以后在软件开着的情况下禁止重连。必须重开软件重连
			idx = szDevId.ReverseFind(_T('#'));
			szDevId.Delete(0, idx + 1);
#ifdef ONLINE
			SetTimer(1, 2000, NULL);
#endif
			//EnumerateEndpointForTheSelectedDevice(DBT_DEVICEARRIVAL, szDevId);
//
		
			

		}
		else if (wParam == DBT_DEVICEREMOVECOMPLETE && lpdb->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
		{
			
			//拔出
			PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)lpdb;
			ASSERT(lstrlen(pDevInf->dbcc_name) > 4);
			CString szDevId = pDevInf->dbcc_name + 4;
			int idx = szDevId.ReverseFind(_T('#'));
			ASSERT(-1 != idx);
			szDevId.Truncate(idx);


			idx = szDevId.ReverseFind(_T('#'));
			szDevId.Delete(0, idx + 1);
			
			//SurveyExistingDevices();
		//	if (AnyprogRunning(0xFF))
			//	return CFrameWnd::DefWindowProc(message, wParam, lParam);

			EnumerateEndpointForTheSelectedDevice(DBT_DEVICEREMOVECOMPLETE, szDevId);


		}
		else
		{
			int k = wParam;
		}
		lpdb->dbch_devicetype;
		lpdb->dbch_size;
	}
	return CFrameWnd::DefWindowProc(message, wParam, lParam);
}
void CMainFrame::OnUpdateMenuAutoRun(CCmdUI* pCmdUI)
{
	//pFormView3->RichEditShow(0, L"111 is busy\n", COLOR_RED, 0, 0);
	//static int k = 0;
	//pCmdUI->SetCheck(1);
	// 
	if (nAutoSenseAutoRun)
	{
		pCmdUI->SetCheck(nAutoSenseAutoRunStartEnd % 2);
		
	}
	else
	{
		pCmdUI->SetCheck(0);
	}
	//k++;
}
void CMainFrame::OnUpdateMenuCancel(CCmdUI* pCmdUI)
{
	
	if (nAutoSenseAutoRun)
	{
		pCmdUI->Enable(0);

	}
	else
	{
		pCmdUI->Enable(1);
	}

}
void CMainFrame::OnMenuFun1()
{
	OpenFileOpenDialog(L"", L"", -1, L"0", L"0",0,0);
}
//
#define SIZE32MB 0X2000000
int CMainFrame::CreateEmptyBuffer(int nBufferIdx,STU_DEVICE_INFO stuDeviceInfoT)
{
	int l = 0,i;
	UCHAR *pDataFill = (UCHAR *)malloc(SIZE32MB);
	memset(pDataFill, 0xff, SIZE32MB);
	TCHAR wszTemp[MAX_PATH];
	char szTemp[MAX_PATH];
	CFileException e;
	CFile64 bufferfile;
	ULONGLONG llbufferlen;
	UINT remainKB, remainMB;
	memset(stu_progdll.swzBufNameArrs, 0, sizeof(stu_progdll.swzBufNameArrs));
	memset(stu_progdll.llBufSizeArrs, 0, sizeof(stu_progdll.llBufSizeArrs));
	memset(stu_dlfiledll.szFileNameArrs, 0, sizeof(stu_dlfiledll.szFileNameArrs));

	memset(stu_dlfiledll.szBufNameArrs, 0, sizeof(stu_dlfiledll.szBufNameArrs));
	memset(stu_dlfiledll.llBufSizeArrs, 0, sizeof(stu_dlfiledll.llBufSizeArrs));
	for (l = 0; l <BUFNUM;l++)
	{
		memset(g_wszFilePathArr[l], 0, sizeof(g_wszFilePathArr[l]));
		if (strlen(stuDeviceInfoT.szBufNameArrs[l]) && strlen(stuDeviceInfoT.szBufSizeArrs[l]))
		{
			if ((nBufferIdx == 0xff) || (nBufferIdx == l))
			{
				wcscpy_s(wszTemp, g_wszCurPath);
				wcscat_s(wszTemp, L"lib\\");
				CharToTchar(wszTemp + wcslen(wszTemp), stuDeviceInfoT.szBufNameArrs[l]);
				wcscat(wszTemp, L".bf");
				wcscpy_s(g_wszFilePathArr[l], L"");

				wcscpy_s(stu_progdll.swzBufNameArrs[l], wszTemp);
				TcharToChar(stu_dlfiledll.szBufNameArrs[l], wszTemp);




				//CharToTchar(wszTemp, stuDeviceInfoT.szBufNameArrs[l]);
				//直接快速创建文件，不填充
				if (!bufferfile.Open(wszTemp, GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
				{
					free(pDataFill);
					return-1;
				}
				sscanf(stuDeviceInfoT.szBufSizeArrs[l], "%I64x", &llbufferlen);
				stu_progdll.llBufSizeArrs[l] = llbufferlen;
				stu_dlfiledll.llBufSizeArrs[l] = llbufferlen;
				remainKB = remainMB = llbufferlen;
				if (1 == strcmp(stuDeviceInfoT.szBufValueArrs[l], "0"))
				{

					if (remainMB > SIZE32MB)
					{
						remainKB = remainMB;

						for (i = 0; i < (remainMB / SIZE32MB); i++)
						{
							bufferfile.Write(pDataFill, SIZE32MB);
							remainKB -= SIZE32MB;
						}

					}

					//剩余的空间填充
					if (remainKB)
					{

						bufferfile.Write(pDataFill, remainKB);

					}
				}
				//0填充直接SETLENGTH
				else
				{
					bufferfile.SetLength(llbufferlen);

				}
				bufferfile.Close();
			}
			
			
		}

	}
	free(pDataFill);
	return 0;
}

HANDLE hProcess;
HWND apphWnd = NULL;
int CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
	DWORD pID;
	DWORD tpID = GetWindowThreadProcessId(hwnd, &pID);
	if (tpID == (DWORD)lParam)
	{
		apphWnd = hwnd;
		return false;
	}
	return true;
}
HANDLE StartProcess(LPCTSTR program, LPCTSTR args)
{
	HANDLE hPro = NULL;
	apphWnd = NULL;
	PROCESS_INFORMATION processInfo;
	STARTUPINFO startupInfo;
	::ZeroMemory(&startupInfo, sizeof(startupInfo));
	startupInfo.cb = sizeof(startupInfo);
	//设置进程创建时不显示窗口
	//startupInfo.dwFlags = /*STARTF_USEPOSITION*/STARTF_USESHOWWINDOW;
	startupInfo.dwX = 600;
	startupInfo.dwY = 900;
	//startupInfo.wShowWindow = SW_HIDE;
	if (::CreateProcess(NULL, (LPTSTR)args,
		NULL,  // process security
		NULL,  // thread security
		FALSE, // no inheritance
		0,     // no startup flags
		NULL,  // no special environment
		NULL,  // default startup directory
		&startupInfo,
		&processInfo))
	{
		//Sleep(500);
		while (!apphWnd)
		{
			apphWnd=FindWindow(NULL, L"HexEdit");
		}
		//while (true)
		{
		//	::EnumWindows(&EnumWindowsProc, processInfo.dwThreadId);//Iterate all windows
			if (NULL != apphWnd)
			{
				int screenWidth = GetSystemMetrics(SM_CXSCREEN);
				int screenHeight = GetSystemMetrics(SM_CYSCREEN);
				int windowX = (screenWidth - 650) / 2;
				int windowY = (screenHeight - 510) / 2;
				SetWindowLong(apphWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW & ~WS_MINIMIZEBOX & ~WS_MAXIMIZEBOX);
			//	SetWindowLong(apphWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW/*GetWindowLong(dia.m_hWnd, GWL_STYLE) & ~WS_CAPTION*/);
				::MoveWindow(apphWnd, windowX, windowY, 0, 0, true);
				
			//	::UpdateWindow(apphWnd);
				::SetWindowPos(apphWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
				//::SetWindowPos(apphWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
				::ShowWindow(apphWnd, SW_SHOW);
			//	HWND hwwwd=FindWindow(L"Qt5152QWindowIcon3", NULL);
			//	break;
			}
				
		}
		hPro = processInfo.hProcess;
	}
	/*
	WaitForSingleObject(processInfo.hProcess, INFINITE);
	GetExitCodeProcess(processInfo.hProcess, &dwResult);
	if (0 != dwResult)
	{

	}
	*/
	return hPro;
}
void CMainFrame::ShowHexDialog(int nBufCnt,TCHAR* pWChar)
{
	CString command;
	command = pWChar;
	TCHAR swztmp[30];
	TCHAR swzCmd[1024];
	DWORD dwBufModifyflag = 0;
	CDialogHide dialogHide;
	int i;
	LPCTSTR lpctstr = command;
	hProcess = StartProcess(NULL, lpctstr);
	if (apphWnd != NULL)
	{
		::SetParent(apphWnd, dialogHide.m_hWnd);

		dialogHide.m_hwdQtHexDlg = apphWnd;
		dialogHide.m_hwd808iApp = GetSafeHwnd();
		dialogHide.DoModal();
		WaitForSingleObject(hProcess, INFINITE);
		GetExitCodeProcess(hProcess, &dwBufModifyflag);
		if (0 != dwBufModifyflag)
		{
#if 1
			//有修改的BUFFER要重新算CHECKSUM
			int nReverseIdx = nBufCnt;
			llTotalCheckSumFile = 0;
			for (i = 0; i < BUFNUM; i++)
			{
				if (strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]) && strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[i]) && (pstuDevInfo[g_curDeviceSel].cIsBufferHide[i] == 0))
				{
					if (dwBufModifyflag & (1 << (nBufCnt - 1)))
					{
						wcscpy(swzCmd, g_wszCurPath);
						CharToTchar(swztmp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);
						wsprintf(swzCmd + wcslen(swzCmd), L"lib\\%s.bf ", swztmp);

						llCheckSumBuf[i] = CProgFileDialog::GetFileChecksum(swzCmd);

						wcscpy(g_wszFilePathArr[i], swzCmd);
						pFormView2->DispEachBufListCtrl(i, llCheckSumFile[i], llCheckSumBuf[i]);

						//pThis->llCheckSumBuf = pThis->GetFileChecksum(wszTemp);
					}
					llTotalCheckSumFile += llCheckSumBuf[i];
				}
			}
			pFormView2->DispAllBufListChecksum();
#endif
		}
	}
	else
		MessageBox(_T("Cannot find Window"));
	return;
}
void CMainFrame::OnMenuBufEdit()
{
	int i,nbufcnt=0;
	char szBufpath[256];
	TCHAR swzCmd[1024];
	TCHAR swztmp[30];
	
	if (g_curDeviceSel == -1)return;
	if (AnyprogRunning(0xFF))
	{
		pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
		return;
	}

	if (strlen(pstuDevInfo[g_curDeviceSel].szLdFileDllName))
	{
		//no EDITABLE 不允许使能
		wcscpy(swzCmd, L"hexedit.exe XC123 0 ");  
	}
		
	else
		wcscpy(swzCmd, L"hexedit.exe XC123 1 ");
	for (i = 0; i < BUFNUM; i++)
	{
		if (strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]) && strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[i])&& (pstuDevInfo[g_curDeviceSel].cIsBufferHide[i]==0))
		{
			nbufcnt++;
		}
	}
	
	//8BIT OR 16BIT 
	wsprintf(swzCmd + wcslen(swzCmd), L"%d 0 ", nbufcnt);
	//OFFSET
	for (i = 0; i < BUFNUM; i++)
	{
		if (strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]) && strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[i]) && (pstuDevInfo[g_curDeviceSel].cIsBufferHide[i] == 0))
		{
			//CharToTchar(swztmp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);
		//	wsprintf(swzCmd + wcslen(swzCmd), L" %x", pstuDevInfo[g_curDeviceSel].nBufBaseAddr[i]);
			wsprintf(swzCmd + wcslen(swzCmd), L" %x", 0);
		}
	}
	//PATH
	for (i = 0; i < BUFNUM; i++)
	{
		if (strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]) && strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[i]) && (pstuDevInfo[g_curDeviceSel].cIsBufferHide[i] == 0))
		{
			CharToTchar(swztmp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);
			wsprintf(swzCmd + wcslen(swzCmd), L" \"%slib\\%s.bf\"", g_wszCurPath,swztmp);
		}
	}
	
	
	ShowHexDialog(nbufcnt, swzCmd);

}
void CMainFrame::OnMenuRemoteControl()
{
	//if (g_curDeviceSel == -1)return;
	if (AnyprogRunning(0xFF))
	{
		pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
		return;
	}
	CRemoteCtrlDlg remoteDlg;
	remoteDlg.DoModal();
}
void CMainFrame::OnMenuHelp()
{
	if (g_curDeviceSel >= 0)
	{
		if (strlen(pstuDevInfo[g_curDeviceSel].szHelpName))
		{
			

				//采用成员变量创建一个非模态对话框
				pHlpDlg = new CHelpDialog(); //给指针分配内存

				wcscpy_s(pHlpDlg->m_swzHelpPath, g_wszCurPath);
				wcscat(pHlpDlg->m_swzHelpPath, L"hlp\\");

				CharToTchar(pHlpDlg->m_swzHelpPath + wcslen(pHlpDlg->m_swzHelpPath), pstuDevInfo[g_curDeviceSel].szHelpName);
			pHlpDlg->Create(IDD_HELPDIALOG); //创建一个非模态对话框
			pHlpDlg->ShowWindow(SW_SHOWNORMAL); //显示非模态对话框

			

		}
	}
	
	
}
void CMainFrame::OnMenuGeneralSetting()
{
	int i;
	if (g_curDeviceSel == -1)return;
	CString str;
	if (AnyprogRunning(0xFF))
	{
		pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
		return;
	}
	str.LoadStringW(IDS_STRING_GNSETTING);
	
	CGNPropSheet ps1(str, this);//对话框标题
	
	memcpy(ps1.m_Page1.m_szVCC, m_szVCC, sizeof(m_szVCC));
	memcpy(ps1.m_Page1.m_szVIO, m_szVIO, sizeof(m_szVIO));
	
	//m_stu_GenSetting 赋值
	ps1.m_Page2.m_stu_GenSetting = stu_GenSetting;
	//默认读文件路径
	for (i = 0; i < BUFNUM; i++)
	{
		ps1.m_Page1.strReadtoPath[i] = m_strReadFileDefaultPath[i];
	}
	

	ps1.m_Page1.m_nPinChkAuto = nAutoSenseAutoRun;
	INT_PTR nResponse = ps1.DoModal();
	 
	if (nResponse == IDOK)
	{
		nAutoSenseAutoRun = ps1.m_Page1.m_nPinChkAuto;
		stu_GenSetting=ps1.m_Page2.m_stu_GenSetting;
		pFormView1->DisplayDeviceInfoInleft();
		memcpy(m_szVCC, ps1.m_Page1.m_szVCC,sizeof(m_szVCC));
		memcpy(m_szVIO, ps1.m_Page1.m_szVIO, sizeof(m_szVIO));
		for (i = 0; i < BUFNUM; i++)
		{
			m_strReadFileDefaultPath[i] = ps1.m_Page1.strReadtoPath[i];	
		}


		DispGeneralSetting();
		//str.Format(L"Erase when blank fail=%d", g_nEraseWhenNOTBlank);
	//	pFormView3->RichEditShow(0, str, COLOR_GHOSTWHITE, CFE_BOLD, 0);
	//	pFormView3->RichEditShow(0, STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
		//pFormView3->RichEditShow(0, L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);
		
	}
	//AfxGetApp()->m_pMainWnd = this;
	//如果要让你的对话框显的更漂亮，可以增加以下代码
	//CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
}

void CMainFrame::OnMenuAutoSeq()
{
	TCHAR wszTmp[2048] = {0};
	if (g_curDeviceSel == -1)return;
	int i = 0, j = 0;
	if (AnyprogRunning(0xFF))
	{
		pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
		return;
	}
//	if (g_isProgramOnline)
	{
		CAUTOSEQDIALOG AutoSeqDlg;
		if (IDOK == AutoSeqDlg.DoModal())
		{
			wcscpy_s(wszTmp, L"Edit Auto:");
			for (i = 0; i < stu_AutoSeqGlob.nAutoCnt; i++)
			{
				if(i)wcscat(wszTmp, L"->");
				CharToTchar(wszTmp + wcslen(wszTmp), stu_FuncList.szFunListArr[stu_AutoSeqGlob.nAutoidxArray[i]]);
				
			}
			pFormView3->RichEditShowAll(0,wszTmp, COLOR_GHOSTWHITE, 0, 0);
			pFormView1->DisplayDeviceInfoInleft();
		}
	}
}
int CMainFrame::AutoRunSingle(int nProIdx)
{
	int err = 0,i=0;
	if ((nProIdx > 7) && (nProIdx < 0))
	{
		AfxMessageBox(L"Invalid ProNum");
		return -1;
	}

	if (g_curDeviceSel == -1)return -1;
	
	if (g_isProgramOnline)
	{
		if (AnyprogRunning(1 << nProIdx))
		{
			pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
			return -1;
		}

	

		if (0 == stu_AutoSeqGlob.nAutoCnt)
		{
			pFormView3->RichEditShow(0, L"No Auto\n", COLOR_RED, 0, 0);
			//确保串口能够再次AUTO
			g_SerialResBuf[m_nSiteNo[nProIdx] - 1] == SER_PROG_READY;
			return -1;
		}

		
		
		if (1 == stu_overlapini.nIsOverLapCheck)
		{
			if ('v' != stu_FuncList.cFuncAttr[stu_overlapini.nOverLapCheckIdx])
			{
				if (0 == wcscmp(g_swzLanguage, L"zh_CN"))
				{
					AfxMessageBox(L"无效的OverLapCheckIdx");
				}
				else if (0 == wcscmp(g_swzLanguage, L"en_US"))
				{
					AfxMessageBox(L"Invalid OverLapCheckIdx");
				}
				
				return -1;
			}
		}
		stu_overlap.nIsOverLapCheck[nProIdx] = stu_overlapini.nIsOverLapCheck;
		stu_overlap.nOverLapCheckIdx = stu_overlapini.nOverLapCheckIdx;
		memset(stu_overlap.nOverLapSockFail, 0, sizeof(stu_overlap.nOverLapSockFail));

		if (1 == g_nEraseWhenNOTBlank)
		{
			if (stu_AutoSeqGlob.nAutoCnt < 2)
			{
				err = 1;

			}
			else
			{
				if (('b' != stu_FuncList.cFuncAttr[stu_AutoSeqGlob.nAutoidxArray[0]]) || ('e' != stu_FuncList.cFuncAttr[stu_AutoSeqGlob.nAutoidxArray[1]]))
				{
					err = 1;
				}
			}
			if (err == 1)
			{
				
				if (0 == wcscmp(g_swzLanguage, L"zh_CN"))
				{
					AfxMessageBox(L"Erase_When_BlankCheckFail=1\n请务必保证AUTO第一项\"空检查\"，第二项\"擦除\"");
				}
				else if (0 == wcscmp(g_swzLanguage, L"en_US"))
				{
					AfxMessageBox(L"Erase_When_BlankCheckFail=1,Please make sure that the first item of AUTO is blankcheck and the second item is erase");
				}
				return -1;
			}
		}
			
		stu_AutoSeq[nProIdx] = stu_AutoSeqGlob;
		stu_UsbDeviceArr[nProIdx].nSockProgStatus = 0;
		//memset(&stu_UserSNProg[nProIdx], 0, sizeof(stu_UserSNProg[nProIdx]));

		m_nIsAuto[nProIdx] = 0xff;
		RunUsbDataProc(1 << nProIdx,0xff);
			
		return 0;
		}
		

	
}

void CMainFrame::OnMenuAutoRun()
{
	
	
	if (g_curDeviceSel == -1)return;
	int i = 0,j=28;
	int err=0;
	if (g_isProgramOnline)
	{

		if (nAutoSenseAutoRun)
		{

			nAutoSenseAutoRunStartEnd++;
			//停止PINCHECK AUTO
			if ((0 == (nAutoSenseAutoRunStartEnd % 2)))
			{
				return;
			}
			else
			{
				pFormView3->RichEditShowAll(0,L"Auto Sensing Begin", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
				memset(nAutoLoopFirst, 0, sizeof(nAutoLoopFirst));
			}
			
		}
		if (AnyprogRunning(0xFF))
		{
			pFormView3->RichEditShowAll(0, L"system is busy\n", COLOR_RED, 0, 0);
			return;
		}

/*
		for (i = 0; i < PROGRAMERMAXNUM; i++)
		{
			j = 0;
			stu_AutoSeqGlob.nAutoCnt = 50;
			//j = 800-1;
			//for (j = 800 - 1; j >= 0; j--)
			while (j<100)
			{
				stu_AutoSeqGlob.nAutoidxArray[j++] = 0;
				stu_AutoSeqGlob.nAutoidxArray[j++] = 1;
				
			}
		}
		
*/
		
		if (1 == stu_overlapini.nIsOverLapCheck)
		{
			if ('v' != stu_FuncList.cFuncAttr[stu_overlapini.nOverLapCheckIdx])
			{
				if (0 == wcscmp(g_swzLanguage, L"zh_CN"))
				{
					AfxMessageBox(L"无效的OverLapCheckIdx");
				}
				else if (0 == wcscmp(g_swzLanguage, L"en_US"))
				{
					AfxMessageBox(L"Invalid OverLapCheckIdx");
				}
				return;
			}
		}
		for (i = 0; i < PROGRAMERMAXNUM; i++)
		{
			stu_overlap.nIsOverLapCheck[i] = stu_overlapini.nIsOverLapCheck;
		}
		
		stu_overlap.nOverLapCheckIdx = stu_overlapini.nOverLapCheckIdx;
		memset(stu_overlap.nOverLapSockFail, 0, sizeof(stu_overlap.nOverLapSockFail));


 		if (0 == stu_AutoSeqGlob.nAutoCnt)
		{
			pFormView3->RichEditShow(0, L"No Auto\n", COLOR_RED,0,0);
			return;
		}
		
		for (i = 0; i < PROGRAMERMAXNUM; i++)
		{

			stu_AutoSeq[i] = stu_AutoSeqGlob;
			stu_UsbDeviceArr[i].nSockProgStatus = 0;
			for (j = 0; j < 10; j++)
			{
				stu_UserSNProg[i][j].nSnNum = 0;
				memset(stu_UserSNProg[i][j].swzSnUsedFile, 0, sizeof(stu_UserSNProg[i][j].swzSnUsedFile));
			}
			
			
		}

		memset(m_nIsAuto, 0xff, sizeof(m_nIsAuto));
		if (1 == g_nEraseWhenNOTBlank)
		{
			if (stu_AutoSeqGlob.nAutoCnt < 2)
			{
				err = 1;

			}
			else
			{
				if (('b' != stu_FuncList.cFuncAttr[stu_AutoSeqGlob.nAutoidxArray[0]]) || ('e' != stu_FuncList.cFuncAttr[stu_AutoSeqGlob.nAutoidxArray[1]]))
				{
					err = 1;
				}
			}
			if (err == 1)
			{
				if (0 == wcscmp(g_swzLanguage, L"zh_CN"))
				{
					AfxMessageBox(L"Erase_When_BlankCheckFail=1\n请务必保证AUTO第一项\"空检查\"，第二项\"擦除\"");
				}
				else if (0 == wcscmp(g_swzLanguage, L"en_US"))
				{
					AfxMessageBox(L"Erase_When_BlankCheckFail=1,Please make sure that the first item of AUTO is blankcheck and the second item is erase");
				}
				return ;
			}
		}
		if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
			RunUsbDataProc(0xffff,0xff);
		else
		{
			
			
			RunUsbDataProc(0xff, 0xff);
		}
		

	}
}
int CMainFrame::PrjLoad(CString strSavePrjPath,int nIsOldPrj)
{
	int i;
	TCHAR wszTemp[MAX_PATH],wszTemp1[100];
	int nConfigPrj[256];
	int nData;
	UINT* pUInt;
	int ret;
#if 1

	//使能会载入没开通SN后载入工程报SN UNAVAILABLE
	CDeviceSelectDialog devseldlg;
	devseldlg.DeviceSelect(0);
#endif
	ret = GetInfoFromPrjFile(strSavePrjPath, 1);
	if (0> ret)
	{
		return ret;
	}
	
		
	
	
	CtrlIDDef();
	
	//curSocketUnit必须给所有的PROG复制，因为剩余的stu_UsbDeviceArr都有可能被插拔征用。那时候如果
	//curSocketUnit是0,那么就不会显示绿色LED
	pFormView2->IconInit();
	//要在这里赋值，下面会用到
	stu_ProjectStatus.nIsInPrj = 1;
	memcpy(nConfigPrj, m_cDownData[0], sizeof(nConfigPrj));
	//兼容之前的数据结构，原来是INT,就用第四位
	pUInt = (UINT*)&m_cDownData[0][(CONFIGWORDSIZE + 1) * 4];
	for(i=0;i< sizeof(m_ullRealFileSize)/sizeof(m_ullRealFileSize[0]);i++)
	{
		m_ullRealFileSize[i] = (UINT)pUInt[i];
	}
	//memcpy(m_ullRealFileSize, &m_cDownData[0][(CONFIGWORDSIZE + 1) * 4], sizeof(m_ullRealFileSize)/2);
	//
	for (i = 0; i < sizeof(m_szVCC) / sizeof(m_szVCC[0]); i++)
	{
		memcpy(&nData, &m_cDownData[0][(CONFIGWORDSIZE + 1 + BUFNUM + 3 + 144 * 3 + i) * 4], sizeof(nData));
		sprintf_s(m_szVCC[i], "%d", nData);
	}
	for (i = 0; i < sizeof(m_szVIO) / sizeof(m_szVIO[0]); i++)
	{
		memcpy(&nData, &m_cDownData[0][(CONFIGWORDSIZE + 1 + BUFNUM + 3 + 144 * 3 + 6 + i) * 4], sizeof(nData));
		sprintf(m_szVIO[i], "%d", nData);
	}

	//加载configword from configword.con
	wcscpy_s(wszTemp, g_wszCurPath);
	wcscat_s(wszTemp, L"lib\\");
	if (nIsOldPrj)
	{
		wcscat_s(wszTemp, L"prj\\");
	}
	if (0 == strcmp("", pstuDevInfo[g_curDeviceSel].szConfig))
	{
		//没有CONFIG，用默认的
		strcpy(pstuDevInfo[g_curDeviceSel].szConfig, "C_DUMMY");

	}
	CharToTchar(wszTemp + wcslen(wszTemp), pstuDevInfo[g_curDeviceSel].szConfig);
	GetConfigFromFile(wszTemp, nConfigPrj);


	for (i = 0; i < PROGRAMERMAXNUM; i++)
	{
		if (stu_UsbDeviceArr[i].status != USBNOTCONNECT)
		{
			g_SerialResBuf[m_nSiteNo[i]-1] = SER_PROG_READY;
		}
	}
	pFormView1->m_tabCtrl.SetCurSel(0);
	if (0 == pFormView1->m_tabCtrl.GetCurSel())
	{
		ReadAlgo_Fpga_ConfigFromFile2Buf(1, nIsOldPrj);
		int idx = 0;
		//查看当前操作项名称和工程里的操作项名称是否匹配
		if (stu_AutoSeqGlob.nAutoCnt)
		{
			for (i = 0; i < stu_AutoSeqGlob.nAutoCnt; i++)
			{
				//只开了10个。超过不比了
				if (i == 10)break;
				//当前NAME
				pFormView1->GetDlgItem(pFormView1->PROCBTN_ARR[stu_AutoSeqGlob.nAutoidxArray[i]])->GetWindowTextW(wszTemp, sizeof(wszTemp) / sizeof(wszTemp[0]));
				//以前的工程没有stu_ProjectHead.szAutoArrName,都是0，兼容考虑
				if (strlen(stu_ProjectHead.szAutoArrName[idx]))
				{
					CharToTchar(wszTemp1, stu_ProjectHead.szAutoArrName[idx]);

					if (wcsncmp(wszTemp, wszTemp1,19))
					{
						//AfxMessageBox(L"Left function name in prj file not match with current");
						pFormView3->RichEditShowAll(0,L"Left function name in prj file not match with current,Auto clear", COLOR_RED, 0, 0);
						stu_AutoSeqGlob.nAutoCnt = stu_AutoSeqGlob.nCurAutoIdx = 0;
						break;
					}
				}
				idx++;

			}
		}
		
	}
	else
	{
		ReadAlgo_Fpga_ConfigFromFile2Buf(0, nIsOldPrj);
	}





	//根据当前器件的UNIT显示
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
	{
		pFormView2->ShowProgPanel16();
	}
	else
	{
		pFormView2->ShowProgPanel();
	}

	//当前选中的programmer，SOCKET MAST赋值
	for (i = 0; i < g_nCustomerDefProgCnt; i++)
	{
		//计数显示初始赋值
		if (i < 6)
		{
			pFormView2->CntDisplayEachPanel(i);
		}

		pFormView1->CntDisplayEachLeftListCtrl(i, 1);
		if (i < 6)
			pFormView2->ChkDisplayEachPanel(i, stu_UsbDeviceArr[i].curSocketUnit, stu_UsbDeviceArr[i].curSocketUnit);
	}

	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
	{
		pFormView2->AutoPosition16();
	}
	else
	{
		pFormView2->AutoPosition();
	}

	//初始化ADAPT NEAR LIMIT弹框计数
	for (i = 0; i < PROGRAMERMAXNUM; i++)
	{
		m_strSktNearLmt[i].Empty();
	}
	memset(&stu_AdptNearLmtDlgTime, 0, sizeof(stu_AdptNearLmtDlgTime));

	return ret;

}
void CMainFrame::OnMenuPrjLoad()
{
	int i = 0, l = 0, j = 0, ret = 0;

	CPrjLoadDialog Loaddlg;
	

	char cBuf[40] = {0};

	CString strSavePrjPath,strLoadPrjName;
	CString strtmp;
	TCHAR wszTmp[MAX_PATH];
	int idx = 0;
	//是否SD插入了，且有效，相同PRJ名字且只有一个
	int nIsALLSDOK=0;


	j = 0; ret = 0; i = 0;
	if (AnyprogRunning(0xFF))
	{
		pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
		return;
	}

	if (Loaddlg.DoModal()== IDOK)
	{
	
		strSavePrjPath = Loaddlg.strLoadPrjPath;
		strLoadPrjName = Loaddlg.strLoadPrjName;
		strtmp = L"Loading project... ";
		pFormView3->RichEditShowAll(0,strtmp, COLOR_GHOSTWHITE, 0, 0);
		pFormView3->RichEditShowAll(0,strSavePrjPath, COLOR_GHOSTWHITE, 0, 0);
		
		
		ret = PrjLoad(strSavePrjPath, 1);

		
		if (0== ret)
		{

			//芯片选择的LOG目录下的LOG路径初始化
			TCHAR wszTemp1[40];
			time_t t = time(0);
			struct tm newtime;
			localtime_s(&newtime, &t);
			//获得按照芯片选择保存LOG的文件名。工程名称+日期+时间
			wsprintf(wszTemp1, L"-%02d%02d%02d%02d%02d%02d", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday, newtime.tm_hour, newtime.tm_min, newtime.tm_sec);
						
			//删掉右边“.ycpj”
			m_strChipSel_PrjName = strLoadPrjName.Left(strLoadPrjName.GetLength() - strlen(".ycpj"));
			m_strChipSel_PrjName += wszTemp1;
			m_nChipSel_Prj = INPRJ;
			int idx = 0;
		


			for (i = 0; i < PROGRAMERMAXNUM; i++)
			{
		
				for (j = 0; j < SOCKETMAX*2; j++)
				{
					stu_UsbDeviceArr[i].colorSocket[j] = pFormView2->hIconGreens[j];				
				}
					
			}
			TCHAR drive[_MAX_DRIVE];
			TCHAR dir[_MAX_DIR];
			TCHAR fname[_MAX_FNAME];
			TCHAR ext[_MAX_EXT];
			CString tmpstr;
			_wsplitpath(strSavePrjPath, drive, dir, fname, ext);
			tmpstr = drive;
			tmpstr += dir;
			if (g_nCustomerDef == CUSTOMERDEF_JIEXING)
			{
				int nDelCnt = DeleteOtherPrjFiles(tmpstr, fname, ext);
				if (nDelCnt)
				{
					tmpstr.Format(L"Delete %d Prj Files", nDelCnt);
					pFormView3->RichEditShowAll(0,tmpstr, COLOR_YELLOW, 0, 0);
				}
			}
			m_bIsPrjEditable = Loaddlg.m_bIsPrjEditable;
		
			pFormView3->RichEditShowAll(0, L"Load project OK", COLOR_GHOSTWHITE, CFE_BOLD, 5);
			
		

			DispSocketStatSum();
		
			pFormView3->DisplayDeviceBrief();
			DisplayBufInfo();
			DispConfigWord(1);
			DispAutoSeq();
			DispGeneralSetting();
			DisplaySocketInfo(stu_ProjectHead.nCurUnitSel);
			
			//
			if (stu_GenSetting.nCnt)
			{
				for (i = 0; i < stu_GenSetting.nCnt; i++)
				{
					strtmp.Format(L"KEY%d,ADDR=0x%08x", i, stu_GenSetting.llAddr[i]);
					pFormView3->RichEditShowAll(0,strtmp, COLOR_GHOSTWHITE, 0, 0);
					CharToTchar(wszTmp, (const char *)stu_GenSetting.szPath[i]);
					
					strtmp.Format(L"PATH=%s", wszTmp);
					pFormView3->RichEditShowAll(0,strtmp, COLOR_GHOSTWHITE, 0, 0);
				
				}

				pFormView3->RichEditShow(0, STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
				pFormView2->DispAllKeyListCtrl();
			
				
			}
			pFormView1->DisplayDeviceInfoInleft();
			

			if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
			{
				pFormView2->AutoPosition16();
			}
			else
			{
				pFormView2->AutoPosition();
			}
			//初始化BUFFER NAME的显示
			int nIdx = 0;
			if (g_curDeviceSel != -1)
			{
				for (i = 0; i < BUFNUM; i++)
				{
					if (strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]) && strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[i]))
					{
						if (pstuDevInfo[g_curDeviceSel].cIsBufferHide[i] == 0)
						{
							m_cComboBufSelMap[nIdx++] = i;
						}
					}
				}
			}


			if (50==g_nDebugValue)
			{
				if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
				{
					CWnd* hwnd = FindWindow(NULL, L"SetBalls");
					if (hwnd == NULL)
					{
						if (m_dllhandleConnectDlg)
						{
							typedef bool(*callback)(HWND, int, int, char*);
							callback show = (callback)(GetProcAddress(m_dllhandleConnectDlg, "showBalls"));

							// TODO: 在此添加控件通知处理程序代码

							HWND HD = GetSafeHwnd();
							char* color("green");
							show(HD, 29, 2, color);

							//FreeLibrary(dllHandle);
						}
					}

				}
				
			}



		}
		else
		{
			stu_ProjectStatus.nIsInPrj = 0;
			pFormView3->RichEditShowAll(0,L"Load project err", COLOR_RED, 0, 0);
			pFormView2->ClearDevice();
			g_curDeviceSel = -1;
		}

		

	}
		
	
	pFormView3->RichEditShowAll(0,L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);
	pFormView3->RichEditShowAll(0,L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);

	
	for(i=0;i<PROGRAMERMAXNUM;i++)
	{
		memset(stu_UsbDeviceArr[i].nSokFailCnt, 0, sizeof(stu_UsbDeviceArr[i].nSokFailCnt));
		memset(stu_UsbDeviceArr[i].nSokTotalCnt, 0, sizeof(stu_UsbDeviceArr[i].nSokTotalCnt));
		stu_UsbDeviceArr[i].nTotalFailCnt = 0;
		stu_UsbDeviceArr[i].nTotalCnt = 0;
		
	}

}
///////////////
int nStaIdx = 0;
void decodeSN(char *pChar, int len)
{

	int i;
	for (i = 0; i < len; i++)
	{
		pChar[i] ^= ArrayXor[nStaIdx++];
	}
}
int CMainFrame::ComparestuDeviceInfo(STU_DEVICE_INFO *src, STU_DEVICE_INFO *dest)
{
	int ret = 0,i=0;
	CString strTmp;
	TCHAR wszTemp[100], wszTemp1[100];
	while (1)
	{
		/*
		if ((strcmp(src->szCID[0], dest->szCID[0])) || (strcmp(src->szCID[1], dest->szCID[1])) || (strcmp(src->szCID[2], dest->szCID[2])) || (strcmp(src->szCID[3], dest->szCID[3])))
		{
			
			strTmp.LoadStringW(IDS_LOADPRJ_ERR1);
			if (IDCANCEL == AfxMessageBox(strTmp, MB_OKCANCEL))
			{
				ret = -1;
				break;
			}
			
		}
		*/
		if (strcmp(src->szAlgo, dest->szAlgo))
		{
			CharToTchar(wszTemp, src->szAlgo);
			CharToTchar(wszTemp1, dest->szAlgo);
			strTmp.Format(L"algo:%s not match %s", wszTemp, wszTemp1);
			pFormView3->RichEditShow(0, strTmp, COLOR_YELLOW, 0, 0);
			strTmp=L"algo not match with current,continue with old setting.";
			pFormView3->RichEditShowAll(0, strTmp, COLOR_YELLOW, 0, 0);
			ret = IDYES;
			//ret = AfxMessageBox(strTmp, MB_YESNOCANCEL | MB_TOPMOST| MB_ICONEXCLAMATION);
			//确定，载入旧的配置
			//取消直接返回
			
			if((IDCANCEL == ret)|| (IDYES == ret))
			{
				
				break;
			}
		
		}
		if (strcmp(src->szFpga0, dest->szFpga0))
		{
			CharToTchar(wszTemp, src->szFpga0);
			CharToTchar(wszTemp1, dest->szFpga0);
			strTmp.Format(L"FPGA1:%s not match %s", wszTemp, wszTemp1);
			pFormView3->RichEditShow(0, strTmp, COLOR_YELLOW, 0, 0);
			//strTmp.LoadStringW(IDS_LOADPRJ_ERR3);
			strTmp = L"FPGA0 not match  with current,continue with old setting.";
			//ret = AfxMessageBox(strTmp, MB_YESNOCANCEL | MB_TOPMOST | MB_ICONEXCLAMATION);
			pFormView3->RichEditShowAll(0, strTmp, COLOR_YELLOW, 0, 0);
			ret = IDYES;
			if ((IDCANCEL == ret) || (IDYES == ret))
			{

				break;
			}
		}
		if (strcmp(src->szFpga1, dest->szFpga1))
		{
			CharToTchar(wszTemp, src->szFpga1);
			CharToTchar(wszTemp1, dest->szFpga1);
			strTmp.Format(L"FPGA2:%s not match %s", wszTemp, wszTemp1);
			pFormView3->RichEditShow(0, strTmp, COLOR_YELLOW, 0, 0);
			strTmp = L"FPGA1 not match  with current,continue with old setting.";
			pFormView3->RichEditShowAll(0, strTmp, COLOR_YELLOW, 0, 0);
			ret = IDYES;
			//ret = AfxMessageBox(strTmp, MB_YESNOCANCEL | MB_TOPMOST | MB_ICONEXCLAMATION);
			if ((IDCANCEL == ret) || (IDYES == ret))
			{

				break;
			}
		}
		if (strcmp(src->szFpga2, dest->szFpga2))
		{
			CharToTchar(wszTemp, src->szFpga2);
			CharToTchar(wszTemp1, dest->szFpga2);
			strTmp.Format(L"FPGA2:%s not match %s", wszTemp, wszTemp1);
			pFormView3->RichEditShow(0, strTmp, COLOR_YELLOW, 0, 0);
			strTmp = L"FPGA2 not match  with current,continue with old setting.";
		//	ret = AfxMessageBox(strTmp, MB_YESNOCANCEL | MB_TOPMOST | MB_ICONEXCLAMATION);
			pFormView3->RichEditShowAll(0, strTmp, COLOR_YELLOW, 0, 0);
			ret = IDYES;
			if ((IDCANCEL == ret) || (IDYES == ret))
			{

				break;
			}
		}
		if(strlen(dest->szFpga3))
		{
			if (strcmp(src->szFpga3, dest->szFpga3))
			{
				if (strncmp(src->szFpga3, "F_ALLPINHIGHZ", strlen("F_ALLPINHIGHZ")) || strncmp(dest->szFpga3, "F_ALLPINHIGHZ", strlen("F_ALLPINHIGHZ")))
				{
					CharToTchar(wszTemp, src->szFpga2);
					CharToTchar(wszTemp1, dest->szFpga2);
					strTmp.Format(L"FPGA3:%s not match %s", wszTemp, wszTemp1);
					pFormView3->RichEditShow(0, strTmp, COLOR_YELLOW, 0, 0);
					strTmp = L"FPGA3 not match  with current,continue with old setting.";
					//ret = AfxMessageBox(strTmp, MB_YESNOCANCEL | MB_TOPMOST | MB_ICONEXCLAMATION);
					pFormView3->RichEditShowAll(0, strTmp, COLOR_YELLOW, 0, 0);
					ret = IDYES;
					if ((IDCANCEL == ret) || (IDYES == ret))
					{

						break;
					}
				}

			}
		}
		
		for (i = 0; i < sizeof(src->nParInts) / sizeof(src->nParInts[0]); i++)
		{
			if (src->nParInts[i]!=dest->nParInts[i])
			{
				strTmp.Format(L"ParInt not match");
				pFormView3->RichEditShow(0, strTmp, COLOR_YELLOW, 0, 0);
			//	strTmp.LoadStringW(IDS_LOADPRJ_ERR7);
				strTmp = L"PARINT not match  with current,continue with old setting.";
				pFormView3->RichEditShowAll(0, strTmp, COLOR_YELLOW, 0, 0);
				ret = IDYES;
				if ((IDCANCEL == ret) )
				{
					break;
				}
				else if (IDYES == ret)
				{
					return ret;
				}
			}
		}

	
		if (strcmp(src->szConfig, dest->szConfig))
		{
			CharToTchar(wszTemp, src->szConfig);
			CharToTchar(wszTemp1, dest->szConfig);
			strTmp.Format(L"FPGA3:%s not match %s", wszTemp, wszTemp1);
			pFormView3->RichEditShow(0, strTmp, COLOR_YELLOW, 0, 0);
			//strTmp.LoadStringW(IDS_LOADPRJ_ERR8);
			strTmp = L"config not match  with current,continue with old setting.";
		//	ret = AfxMessageBox(strTmp, MB_YESNOCANCEL | MB_TOPMOST | MB_ICONEXCLAMATION);
			pFormView3->RichEditShowAll(0, strTmp, COLOR_YELLOW, 0, 0);
			ret = IDYES;
			if ((IDCANCEL == ret) || (IDYES == ret))
			{

				break;
			}
		}
		/*
		for (i = 0; i < sizeof(src->szVccs) / sizeof(src->szVccs[0]); i++)
		{
			if (strcmp(src->szVccs[i],dest->szVccs[i]))
			{
				strTmp.LoadStringW(IDS_LOADPRJ_ERR9);
				if (IDCANCEL == AfxMessageBox(strTmp, MB_OKCANCEL))
				{
					ret = -1;
					return ret;
				}
			}
		}
		*/
		/*
		for (i = 0; i < sizeof(src->szVccIOs) / sizeof(src->szVccIOs[0]); i++)
		{
			if (strcmp(src->szVccIOs[i], dest->szVccIOs[i]))
			{
				strTmp.LoadStringW(IDS_LOADPRJ_ERR10);
				if (IDCANCEL == AfxMessageBox(strTmp, MB_OKCANCEL))
				{
					ret = -1;
					return ret;
				}
			}
		}
		*/
		
		for(i=0;i< sizeof(src->szBufNameArrs)/sizeof(src->szBufNameArrs[0]);i++)
		{
			if (strcmp(src->szBufNameArrs[i], dest->szBufNameArrs[i]))
			{
				strTmp.Format(L"Bufname not match");
				pFormView3->RichEditShow(0, strTmp, COLOR_RED, 0, 0);
				strTmp.LoadStringW(IDS_LOADPRJ_ERR11);
				strTmp = L"Buf name not match  with current,continue with old setting.";
				//ret = AfxMessageBox(strTmp, MB_YESNOCANCEL | MB_TOPMOST | MB_ICONEXCLAMATION);
				pFormView3->RichEditShowAll(0, strTmp, COLOR_YELLOW, 0, 0);
				ret = IDYES;
				if ((IDCANCEL == ret))
				{
					break;
				}
				else if (IDYES == ret)
				{
					return ret;
				}
			}
		}
		for (i = 0; i < sizeof(src->szBufSizeArrs) / sizeof(src->szBufSizeArrs[0]); i++)
		{
			if (strcmp(src->szBufSizeArrs[i], dest->szBufSizeArrs[i]))
			{
				strTmp.Format(L"Bufsize not match");
				pFormView3->RichEditShow(0, strTmp, COLOR_RED, 0, 0);
				//strTmp.LoadStringW(IDS_LOADPRJ_ERR12);
				strTmp = L"Buf size not match  with current,continue with old setting";
				//取消也返回IDOK
				//ret = AfxMessageBox(strTmp, MB_OK | MB_TOPMOST | MB_ICONEXCLAMATION);
				pFormView3->RichEditShowAll(0, strTmp, COLOR_YELLOW, 0, 0);
				ret = IDYES;
				if (IDOK == ret)
				{
					ret = IDYES;
					return ret;
				}
				
			}
		}
		
		break;
	}

	return ret;
}
//获得STU_INFODEVICE。恢复buffer，生成ALGO,FPGA，config等文件在PRJ目录下
int CMainFrame::GetInfoFromPrjFile(CString strPrjPath,int nIsOldPrj)
{
	int k=0,i=0,l=0;
	int ret;
	ULONGLONG llchecksum=0,llBuflen=0;
	int nbarsteplen;
	int rdlen;
	CFile prjfile;
	TCHAR wzbuf[MAX_PATH];
	TCHAR wszTemp[256], wszTemp1[256], wszTemp2[256];
	TCHAR wszFilename[50];
	char sztmp[MAX_PATH];
	CFile DesFile;
	//STU_PRJHEAD temp_stu_PrjHead;
	STU_DEVICE_INFO stu_prjDeviceInfo;
	STU_DEVICE_INFO *pCurDeviceInfo=NULL;
	CString strtmp;
	CProgressBar bar(_T(""), 100, 100, TRUE);
	//tempstu_deviceifo_bak.nDevIdx = -1;
	if (!prjfile.Open(strPrjPath, CFile::modeRead))
	{
		//AfxMessageBox(L"prj open error");
		return -1;
	}

	/***********HEAD+DEVICEINFO 合法性判断和赋值***************/
	//MAGIC
	prjfile.Read(&stu_ProjectHead, sizeof(stu_ProjectHead));
	if (0 != memcmp(stu_ProjectHead.szMagic, "MYPJ", strlen("MYPJ")))
	{	
		prjfile.Close();
		pFormView3->RichEditShowAll(0,L"PRJ migic not match", COLOR_RED, 0, 0);
		return -2;

	}


	//HEADLEN
	if(stu_ProjectHead.nHeadLen!=sizeof(stu_ProjectHead))
	{
		AfxMessageBox(L"PRJ head len not match");
		prjfile.Close();
		return -3;
	}
	//deviceinfo len
	if(stu_ProjectHead.nLenStuDeviceInfo!=sizeof(STU_DEVICE_INFO))
	{
		AfxMessageBox(L"Device info len not match");
		prjfile.Close();
		return -4;
	}
	nStaIdx = 0;
	//copy checksum
	memcpy(llCheckSumFile, stu_ProjectHead.llCheckSumFile, sizeof(llCheckSumFile));
	memcpy(llCheckSumBuf, stu_ProjectHead.llCheckSumBuf, sizeof(llCheckSumBuf));

	llTotalCheckSumBuf = stu_ProjectHead.llTotalCheckSumBuf ;
	llTotalCheckSumFile=stu_ProjectHead.llTotalCheckSumFile ;
	//copy sn 数据结构
	stu_GenSetting=stu_ProjectHead.stu_GenSetting_prj;
	//memset(&stu_GenSetting, 0, sizeof(stu_GenSetting));
	//socketcursel

	for (i = 0; i < g_nCustomerDefProgCnt; i++)
	{
		
			stu_UsbDeviceArr[i].curSocketUnit =stu_ProjectHead.nCurUnitSel;
		
			g_nSocketUnit[i] = stu_ProjectHead.nCurUnitSel;
	}
	g_nEraseWhenNOTBlank = stu_ProjectHead.nEraseWhenBLKFail;
	g_nIsNeedChkId= stu_ProjectHead.nIsIdCheck;
	llchecksum+=CalcCheckSum((PUCHAR)&stu_ProjectHead, sizeof(stu_ProjectHead));
	//stu_device info
	
	prjfile.Read(&stu_prjDeviceInfo,sizeof(stu_prjDeviceInfo));
	

	if (stu_prjDeviceInfo.nIsKeyAvailable&&stu_GenSetting.nCnt)
	{
		if (stu_overlapini.nIsOverLapCheck)
		{
			//pFormView3->RichEditShow(0, L"工程使用KEY，请禁用叠料检测使能", COLOR_RED, 0, 0);
			if (0 == wcscmp(g_swzLanguage, L"zh_CN"))
			{
				AfxMessageBox(L"工程使用KEY，请禁用叠料检测使能");
			}
			else if (0 == wcscmp(g_swzLanguage, L"en_US"))
			{
				AfxMessageBox(L"Overlapcheck fobidden using key programming");
			}
			else
			{
				AfxMessageBox(L"Overlapcheck fobidden using key programming");
			}
			
//			return -5;
		}
	}
	llchecksum+=CalcCheckSum((PUCHAR)&stu_prjDeviceInfo, sizeof(stu_prjDeviceInfo));
#if 1
	//SN CNT 工程里获得SN，废弃。
	int nAvailSnCnt;
	prjfile.Read(&nAvailSnCnt, sizeof(nAvailSnCnt));
	llchecksum += CalcCheckSum((PUCHAR)&nAvailSnCnt, sizeof(nAvailSnCnt));
#if 1
	decodeSN((char*)&nAvailSnCnt, 4);
	strListSN.RemoveAll();
	if (nAvailSnCnt)
	{
		for (i = 0; i < nAvailSnCnt; i++)
		{
			prjfile.Read(sztmp, 16);
			llchecksum += CalcCheckSum((PUCHAR)sztmp, 16);
			decodeSN(sztmp, 16);
		//	sztmp[16] = 0;
	//		CharToTchar(wzbuf, sztmp);
		//	strListSN.AddTail(wzbuf);
		}
	}
#endif
#endif
	/***********选芯片***************/
	wcscpy_s(wzbuf, g_wszCurPath);
	wcscat_s(wzbuf, L"lib\\");
	CharToTchar(wszFilename, stu_prjDeviceInfo.szJsonFileName);
	wcscat(wzbuf, wszFilename);
	//通过工程中的deviceinfo中的JSON文件名读出JSON文件
	
	CString strDest, strSrc = wzbuf;
	strDest = strSrc + L"_";
	
#ifdef ENCODEJSON
	//if (-1 == ReadJson(strDest))//GetInfoFromPrjFile
#else
	DecodeXor(strDest, strSrc);
	if (-1 == ReadJson(strSrc))//GetInfoFromPrjFile
#endif
	
	// 遍历JSON，找到与输入名称相同

	

	//查找是否存在当前的JSON里面,4要素是否相同	
	pFormView3->RichEditShowAll(0, L"Checking Device In JList \n", COLOR_YELLOW, 0, 0);
	int successmask = 0;
	for (i = 0; i < g_nDevInfoCnt; i++)
	{

		if ((0 == strcmp(pstuDevInfo[i].szManufacture, stu_prjDeviceInfo.szManufacture))
			&& (0 == strcmp(pstuDevInfo[i].szDeviceName, stu_prjDeviceInfo.szDeviceName))
			&& (0 == strcmp(pstuDevInfo[i].szPackage, stu_prjDeviceInfo.szPackage))
			&& (pstuDevInfo[i].isIsp == stu_prjDeviceInfo.isIsp))
			break;
	}
	if (g_nDevInfoCnt == i)
	{
		pFormView3->RichEditShowAll(0,L"Chip in prj not match in Device(J) list \n", COLOR_YELLOW, 0, 0);
		prjfile.Close();
		return -6;

	}


	for (k = 0; k < g_nDevInfoCnt; k++)
	{
	
		//选中芯片名称==TXT中的芯片名称,四要素
		if((0==strcmp(stu_prjDeviceInfo.szDeviceName, pstuDevInfo[k].szDeviceName))&&
			(0 == strcmp(stu_prjDeviceInfo.szManufacture, pstuDevInfo[k].szManufacture))&&
				(stu_prjDeviceInfo.isIsp== pstuDevInfo[k].isIsp)&&
				(0 == strcmp(stu_prjDeviceInfo.szPackage, pstuDevInfo[k].szPackage)))
		{
			//保存到全局pstuDevInfo，否则保存工程就没有这个结构。
			g_curDeviceSel = k;
			//工程deviceinfo和当前device info的元素相比
		
			
			
			//一定用旧配置
			if (1 == nIsOldPrj)
			{
		
				pCurDeviceInfo = &stu_prjDeviceInfo;
			}


			//如果是需要用旧配置就恢复工程里的算法
			wcscpy_s(wzbuf, g_wszCurPath);
			
			wcscat_s(wzbuf, L"lib\\");
			wcscpy(wszTemp, wzbuf);
			if (1 == nIsOldPrj)
			{
				wcscat_s(wzbuf, L"prj\\");
			}
			CharToTchar(wszFilename, stu_prjDeviceInfo.szAlgo);
			wcscat(wzbuf, wszFilename);
			//lib目录路径
			wcscat(wszTemp, wszFilename);

			prjfile.Read(gSendbuf, stu_ProjectHead.nLenAlgo);
			llchecksum += CalcCheckSum(gSendbuf, stu_ProjectHead.nLenAlgo);
			if (1 == nIsOldPrj)
			{
				if (!DesFile.Open(wzbuf, CFile::modeCreate | CFile::modeWrite))
				{
					AfxMessageBox(L"Write prj algo file error");

					return -1;
				}
				DesFile.Write(gSendbuf, stu_ProjectHead.nLenAlgo);
				DesFile.Close();
				if (FALSE == CompareFiles(wzbuf, wszTemp))
				{
					strtmp.LoadStringW(IDS_STRING148);
					strtmp += L"@Algo";
					pFormView3->RichEditShowAll(0, strtmp, COLOR_YELLOW, 0, 0);
					//AfxMessageBox(strtmp);
				}
			}

			
			//如果是需要用旧配置就恢复fpga1
			if(strlen(stu_prjDeviceInfo.szFpga0))
			{
				prjfile.Read(gSendbuf,stu_ProjectHead.nLenFpga0);
				llchecksum += CalcCheckSum(gSendbuf, stu_ProjectHead.nLenFpga0);
				//就配置才要恢复文件
				if (1 == nIsOldPrj)
				{
					wcscpy_s(wzbuf, g_wszCurPath);
					wcscat_s(wzbuf, L"lib\\");
					//目的,prj目录
					wcscpy(wszTemp, wzbuf);
					//原始目录
					wcscpy(wszTemp1, wzbuf);
					wcscpy(wszTemp2, wzbuf);
					if ('2' == JudgeFpgaBitPackage(gSendbuf))
					{
						wcscat_s(wzbuf, L"prj\\F2\\");
						wcscat_s(wszTemp, L"prj\\F3\\");
						wcscat_s(wszTemp1, L"F3\\");
						wcscat_s(wszTemp2, L"F2\\");
					}
					else
					{
						wcscat_s(wzbuf, L"prj\\F3\\");
						wcscat_s(wszTemp, L"prj\\F2\\");
						wcscat_s(wszTemp1, L"F2\\");
						wcscat_s(wszTemp2, L"F3\\");
					}
					CharToTchar(wszFilename, stu_prjDeviceInfo.szFpga0);
					wcscat(wzbuf, wszFilename);
					wcscat(wszTemp, wszFilename);
					wcscat(wszTemp1, wszFilename);
					wcscat(wszTemp2, wszFilename);
					CopyFile(wszTemp1, wszTemp, FALSE);
					if (stu_ProjectHead.nLenFpga0)
					{
						if (!DesFile.Open(wzbuf, CFile::modeCreate | CFile::modeWrite))
						{
							prjfile.Close();

							AfxMessageBox(L"Write prj fpga1 file error");
							return -1;
						}
						DesFile.Write(gSendbuf, stu_ProjectHead.nLenFpga0);
						DesFile.Close();
					}
					else
					{
						CopyFile(wszTemp2, wzbuf, FALSE);
					}
				
				}
				
			}
			
			//如果是需要用旧配置就恢复fpga2
			if (strlen(stu_prjDeviceInfo.szFpga1))
			{
				prjfile.Read(gSendbuf, stu_ProjectHead.nLenFpga1);
				llchecksum += CalcCheckSum(gSendbuf, stu_ProjectHead.nLenFpga1);
				//就配置才要恢复文件
				if (1 == nIsOldPrj)
				{
					wcscpy_s(wzbuf, g_wszCurPath);
					wcscat_s(wzbuf, L"lib\\");
					//目的,prj目录
					wcscpy(wszTemp, wzbuf);
					//原始目录
					wcscpy(wszTemp1, wzbuf);
					wcscpy(wszTemp2, wzbuf);
					if ('2' == JudgeFpgaBitPackage(gSendbuf))
					{
						wcscat_s(wzbuf, L"prj\\F2\\");
						wcscat_s(wszTemp, L"prj\\F3\\");
						wcscat_s(wszTemp1, L"F3\\");
						wcscat_s(wszTemp2, L"F2\\");
					}
					else
					{
						wcscat_s(wzbuf, L"prj\\F3\\");
						wcscat_s(wszTemp, L"prj\\F2\\");
						wcscat_s(wszTemp1, L"F2\\");
						wcscat_s(wszTemp2, L"F3\\");
					}
					CharToTchar(wszFilename, stu_prjDeviceInfo.szFpga1);
					wcscat(wzbuf, wszFilename);
					wcscat(wszTemp, wszFilename);
					wcscat(wszTemp1, wszFilename);
					wcscat(wszTemp2, wszFilename);
					CopyFile(wszTemp1, wszTemp, FALSE);
					if (stu_ProjectHead.nLenFpga1)
					{
						if (!DesFile.Open(wzbuf, CFile::modeCreate | CFile::modeWrite))
						{
							prjfile.Close();
							AfxMessageBox(L"Write prj fpga2 file error");
							return -1;
						}
						DesFile.Write(gSendbuf, stu_ProjectHead.nLenFpga1);
						DesFile.Close();
					}
					else
					{
						CopyFile(wszTemp2, wzbuf, FALSE);
					}
				}

			}

			//如果是需要用旧配置就恢复fpga3
			if (strlen(stu_prjDeviceInfo.szFpga2))
			{
				prjfile.Read(gSendbuf, stu_ProjectHead.nLenFpga2);
				llchecksum += CalcCheckSum(gSendbuf, stu_ProjectHead.nLenFpga2);
				//就配置才要恢复文件
				if (1 == nIsOldPrj)
				{
					wcscpy_s(wzbuf, g_wszCurPath);
					wcscat_s(wzbuf, L"lib\\");
					//目的,prj目录
					wcscpy(wszTemp, wzbuf);
					//原始目录
					wcscpy(wszTemp1, wzbuf);

					wcscpy(wszTemp2, wzbuf);
					if ('2' == JudgeFpgaBitPackage(gSendbuf))
					{
						wcscat_s(wzbuf, L"prj\\F2\\");
						wcscat_s(wszTemp, L"prj\\F3\\");
						wcscat_s(wszTemp1, L"F3\\");
						wcscat_s(wszTemp2, L"F2\\");
					}
					else
					{
						wcscat_s(wzbuf, L"prj\\F3\\");
						wcscat_s(wszTemp, L"prj\\F2\\");
						wcscat_s(wszTemp1, L"F2\\");
						wcscat_s(wszTemp2, L"F3\\");
					}
					CharToTchar(wszFilename, stu_prjDeviceInfo.szFpga2);
					wcscat(wzbuf, wszFilename);
					wcscat(wszTemp, wszFilename);
					wcscat(wszTemp1, wszFilename);
					CopyFile(wszTemp1, wszTemp, FALSE);
					if (stu_ProjectHead.nLenFpga2)
					{
						if (!DesFile.Open(wzbuf, CFile::modeCreate | CFile::modeWrite))
						{
							prjfile.Close();
							AfxMessageBox(L"Write prj fpga3 file error");
							return -1;
						}
						DesFile.Write(gSendbuf, stu_ProjectHead.nLenFpga2);
						DesFile.Close();
					}
					else
					{
						CopyFile(wszTemp2, wzbuf, FALSE);
					}
				}

			}
			
			if (1 == nIsOldPrj)
			{
				wcscpy_s(wszTemp, g_wszCurPath);
				wcscat_s(wszTemp, L"lib\\prj\\F2\\F_ALLPINHIGHZ");
				wcscpy_s(wszTemp1, g_wszCurPath);
				wcscat_s(wszTemp1, L"lib\\F2\\F_ALLPINHIGHZ");
				CopyFile(wszTemp1, wszTemp, FALSE);
				wcscpy_s(wszTemp, g_wszCurPath);
				wcscat_s(wszTemp, L"lib\\prj\\F3\\F_ALLPINHIGHZ");
				wcscpy_s(wszTemp1, g_wszCurPath);
				wcscat_s(wszTemp1, L"lib\\F3\\F_ALLPINHIGHZ");
				CopyFile(wszTemp1, wszTemp, FALSE);
				wcscpy_s(wszTemp, g_wszCurPath);
				wcscat_s(wszTemp, L"lib\\prj\\F2\\F_ALLPINHIGHZ_OF");
				wcscpy_s(wszTemp1, g_wszCurPath);
				wcscat_s(wszTemp1, L"lib\\F2\\F_ALLPINHIGHZ_OF");
				CopyFile(wszTemp1, wszTemp, FALSE);
				wcscpy_s(wszTemp, g_wszCurPath);
				wcscat_s(wszTemp, L"lib\\prj\\F3\\F_ALLPINHIGHZ_OF");
				wcscpy_s(wszTemp1, g_wszCurPath);
				wcscat_s(wszTemp1, L"lib\\F3\\F_ALLPINHIGHZ_OF");
				CopyFile(wszTemp1, wszTemp, FALSE);
			}
			//如果是需要用旧配置就恢复fpga4
			if (strcmp(stu_prjDeviceInfo.szFpga3, "F_ALLPINHIGHZ") && strcmp(stu_prjDeviceInfo.szFpga3, "F_ALLPINHIGHZ_OF"))
			{
				if (strlen(stu_prjDeviceInfo.szFpga3))
				{
					prjfile.Read(gSendbuf, stu_ProjectHead.nLenFpga3);
					llchecksum += CalcCheckSum(gSendbuf, stu_ProjectHead.nLenFpga3);
					//就配置才要恢复文件,同时如果有F2和F3的另一部分文件
					if (1 == nIsOldPrj)
					{
						wcscpy_s(wzbuf, g_wszCurPath);
						wcscat_s(wzbuf, L"lib\\");
						//目的,prj目录
						wcscpy(wszTemp, wzbuf);
						//原始目录
						wcscpy(wszTemp1, wzbuf);
						if ('2' == JudgeFpgaBitPackage(gSendbuf))
						{
							wcscat_s(wzbuf, L"prj\\F2\\");
							wcscat_s(wszTemp, L"prj\\F3\\");
							wcscat_s(wszTemp1, L"F3\\");
						}
						else
						{
							wcscat_s(wzbuf, L"prj\\F3\\");
							wcscat_s(wszTemp, L"prj\\F2\\");
							wcscat_s(wszTemp1, L"F2\\");
						}
						CharToTchar(wszFilename, stu_prjDeviceInfo.szFpga3);
						wcscat(wzbuf, wszFilename);
						wcscat(wszTemp, wszFilename);
						wcscat(wszTemp1, wszFilename);
						CopyFile(wszTemp1, wszTemp, FALSE);
						if (!DesFile.Open(wzbuf, CFile::modeCreate | CFile::modeWrite))
						{
							prjfile.Close();
							AfxMessageBox(L"Write prj fpga3 file error");
							return -1;
						}
						DesFile.Write(gSendbuf, stu_ProjectHead.nLenFpga3);
						DesFile.Close();

					}

				}
			}
			
	
			//恢复configfile,用于对比
			wcscpy_s(wzbuf, g_wszCurPath);
			wcscat_s(wzbuf, L"lib\\");
			wcscpy(wszTemp, wzbuf);
			if (1 == nIsOldPrj)
			{
				wcscat_s(wzbuf, L"prj\\");
			}
			CharToTchar(wszFilename, stu_prjDeviceInfo.szConfig);
			wcscat(wzbuf, wszFilename);
			//lib目录路径
			wcscat(wszTemp, wszFilename);
			prjfile.Read(gSendbuf, stu_ProjectHead.nLenConfigFile);
			llchecksum += CalcCheckSum(gSendbuf, stu_ProjectHead.nLenConfigFile);
			if (1 == nIsOldPrj)
			{
				if (!DesFile.Open(wzbuf, CFile::modeCreate | CFile::modeWrite))
				{
					AfxMessageBox(L"Load prj config file error");
					return -1;
				}
				DesFile.Write(gSendbuf, stu_ProjectHead.nLenConfigFile);
				DesFile.Close();
				if (FALSE == CompareFiles(wzbuf, wszTemp))
				{
					strtmp.LoadStringW(IDS_STRING148);
					strtmp += L"@Con";
					pFormView3->RichEditShowAll(0, strtmp, COLOR_YELLOW, 0, 0);
				//	AfxMessageBox(strtmp);
				}
			}


			
			//CONFIGWORD+infopara
			prjfile.Read(m_cDownData[0], stu_ProjectHead.nLenConfigWord_info);
			llchecksum += CalcCheckSum((PUCHAR)m_cDownData[0], stu_ProjectHead.nLenConfigWord_info);



			//AUTO STRUCTURE
			prjfile.Read(&stu_AutoSeqGlob, sizeof(stu_AutoSeqGlob));
			llchecksum += CalcCheckSum((PUCHAR)&stu_AutoSeqGlob, sizeof(stu_AutoSeqGlob));



			g_curDeviceSel = k;
			if (-1 == (CreateEmptyBuffer(0xff, *pCurDeviceInfo)))
			{
				pFormView3->RichEditShowAll(0,L"Create Buffer Fail\n", COLOR_RED, 0, 0);
			}
			for (i = 0; i < BUFNUM; i++)
			{
				CharToTchar(g_wszFilePathArr[i], stu_ProjectHead.szBufferFilePathArr[i]);
			}
			
			pFormView2->DispAllBufListCtrl(*pCurDeviceInfo);
			
			for (i = 0; i < BUFNUM; i++)
			{
			
				if (strlen(stu_prjDeviceInfo.szBufNameArrs[i]) && strlen(stu_prjDeviceInfo.szBufSizeArrs[i]))
				{

					CharToTchar(wszFilename, stu_prjDeviceInfo.szBufNameArrs[i]);
					wcscpy_s(wzbuf, g_wszCurPath);
					wcscat(wzbuf, L"lib\\");
					CharToTchar(wzbuf + wcslen(wzbuf), stu_prjDeviceInfo.szBufNameArrs[i]);
					wcscat(wzbuf, L".bf");
					//wsprintf(wzbuf + wcslen(wzbuf), L"buf%d", i);

					//wcscat(wzbuf, wszFilename);
					//拷贝PRJ中的BUFFER至BURRLERX.
					if (!DesFile.Open(wzbuf, CFile::modeCreate | CFile::modeWrite))
					{
						
						AfxMessageBox(L"Load prj fileopen error");
						return -1;
					}
					sscanf(stu_prjDeviceInfo.szBufSizeArrs[i], "%I64x", &llBuflen);
					nbarsteplen = llBuflen / sizeof(gSendbuf) + 1;
					bar.SetRange(0, nbarsteplen);
					for (l = 0; l < llBuflen / sizeof(gSendbuf); l++)
					{
						rdlen = prjfile.Read(gSendbuf, sizeof(gSendbuf));
						llchecksum += CalcCheckSum(gSendbuf, sizeof(gSendbuf));
						DesFile.Write(gSendbuf, rdlen);
						bar.StepIt();
					}
					int remainfilelen = llBuflen % sizeof(gSendbuf);
					if (remainfilelen)
					{
						prjfile.Read(gSendbuf, remainfilelen);
						llchecksum += CalcCheckSum(gSendbuf, remainfilelen);
						DesFile.Write(gSendbuf, remainfilelen);
						bar.StepIt();
					}
					bar.SetPos(nbarsteplen);
					DesFile.Close();
					CharToTchar(wzbuf, stu_ProjectHead.szBufferFilePathArr[i]);
					wcscpy_s(g_wszFilePathArr[i], wzbuf);
					pFormView2->DispEachBufListCtrl(i, llCheckSumFile[i], llCheckSumBuf[i]);
					pFormView2->DispAllBufListChecksum();
				}
				
			
			}
			
			//烧录文件路径清0
			//memset(g_wszFilePathArr, 0, sizeof(g_wszFilePathArr));
			ULONGLONG llcurChecksum;
			int ttt = prjfile.GetPosition();
			prjfile.Read(&llcurChecksum, sizeof(llcurChecksum));
			bar.Clear();
			if (llcurChecksum != llchecksum)
			{
				
				AfxMessageBox(L"Prj Checksum not match");
				return -1;
				
			}
			pFormView1->DisplayDeviceBrief(*pCurDeviceInfo);
			break;
		}
	}
	if (k == g_nDevInfoCnt)
	{
		
		AfxMessageBox(L"Find no matched device in list");
		return -1;
	}

	//SN
	//CDeviceSelectDialog devseldlg;
//	devseldlg.DeviceSelect(0);
	TCHAR *pswzTemp;
	CString  strTmp;
	
	char szTemp[256];
	#ifdef SPVERSION
	for (i = 0; i < 4; i++)
	{
		//SOCKET CLEAR NAME 有，socket name无，要获得socket name from clear name
		if ((strlen(pstusktname[g_curDeviceSel].szSocketNameClear[i])) && (0 == strlen(pCurDeviceInfo->szSocketName[i])))
		{
			
			CharToTchar(wszTemp, pstusktname[g_curDeviceSel].szSocketNameClear[i]);
			CSktNMMap1.Lookup(wszTemp, strTmp);

			pswzTemp = strTmp.GetBuffer();
			TcharToChar(szTemp, pswzTemp);
			strTmp.ReleaseBuffer();
			strcpy(pCurDeviceInfo->szSocketName[i], szTemp);
				
		}
	}


	//getSocketNameFromClrName  end
	//如果是ISP，并且getSocketNameFromClrName 是空，就不限次数
	if (pCurDeviceInfo->isIsp
		&& (0 == strlen(pstusktname[g_curDeviceSel].szSocketNameClear[0]))
		&& (0 == strlen(pstusktname[g_curDeviceSel].szSocketNameClear[1]))
		&& (0 == strlen(pstusktname[g_curDeviceSel].szSocketNameClear[2]))
		&& (0 == strlen(pstusktname[g_curDeviceSel].szSocketNameClear[3])))
	{
		strcpy(pCurDeviceInfo->szSocketName[3], "LFFF");
	}
	if ((strlen(pCurDeviceInfo->szSocketName[0]) == 0)
		&& (strlen(pCurDeviceInfo->szSocketName[1]) == 0)
		&& (strlen(pCurDeviceInfo->szSocketName[2]) == 0)
		&& (strlen(pCurDeviceInfo->szSocketName[3]) == 0))
	{
	
		AfxMessageBox(L"find no Socket Name");
		return -5;
	}
#endif



	CString strCurDeviceInjson, strCurmanufactureInjson, strPackageInjson, strISPInjson;
	CString strManufacture, strDevname, strPackage, strISP;




	CObject *pObject = NULL;
	CStringList *gpListSN = NULL;

	CharToTchar(wzbuf, pCurDeviceInfo->szDeviceName);
	strCurDeviceInjson.Format(L"%s", wzbuf);
	CharToTchar(wzbuf, pCurDeviceInfo->szManufacture);
	strCurmanufactureInjson.Format(L"%s", wzbuf);
	CharToTchar(wzbuf, pCurDeviceInfo->szPackage);
	strPackageInjson.Format(L"%s", wzbuf);
	wsprintf(wzbuf, L"%d", pCurDeviceInfo->isIsp);
	strISPInjson.Format(L"%s", wzbuf);
	CString strMerge;
	//选中芯片名称==TXT中的芯片名称
	//if ((strCurDeviceInjson == strDevname) && (strCurmanufactureInjson == strManufacture) && (strPackageInjson == strPackage) && (strISPInjson == strISP))
	{
		strMerge = strCurmanufactureInjson;
		strMerge += strCurDeviceInjson;
		strMerge += strPackageInjson;
		strMerge += strISPInjson;
		StrDeviceMap.Lookup(strMerge, pObject);
		gpListSN = (CStringList *)pObject;

		strListSN.RemoveAll();

		//复制CSTRING LIST
		if (gpListSN)
		{
			POSITION rPos = gpListSN->GetHeadPosition();
			while (rPos != NULL)
			{
				strListSN.AddTail(gpListSN->GetNext(rPos));
			}
		}
	}


	CharToTchar(wszTemp, stu_ProjectHead.szCapTime);
	wcscat(wszTemp, L"   ");
	CharToTchar(wszTemp+wcslen(wszTemp), stu_ProjectHead.szSaveTime);
	pFormView3->RichEditShow(0, wszTemp, COLOR_GHOSTWHITE, 0, 0);
	//获得json内的vcc 和VIO，复制到副本，用于修改保存
	memcpy(m_szVCC, pCurDeviceInfo->szVccs, sizeof(pCurDeviceInfo->szVccs));
	memcpy(m_szVIO, pCurDeviceInfo->szVccIOs, sizeof(pCurDeviceInfo->szVccIOs));
	
	//只要不同的INDX，就说明换工程了，那么恢复前一个旧工程的现场
	if (-1 != stu_deviceifo_bak.nDevIdx)
	{
		if (g_curDeviceSel != stu_deviceifo_bak.nDevIdx)
		{
			//换其他芯片工程恢复之前载入工程对应的deviceinf

			memcpy(&pstuDevInfo[stu_deviceifo_bak.nDevIdx], &stu_deviceifo_bak.deviceinfo, sizeof(pstuDevInfo[g_curDeviceSel]));
			stu_deviceifo_bak.nDevIdx = -1;
			

		}
		else
		{
			if (0 == nIsOldPrj)
			{
				//换同芯片工程只有在不是旧配置选择的时候，才恢复
				memcpy(&pstuDevInfo[g_curDeviceSel], &stu_deviceifo_bak.deviceinfo, sizeof(pstuDevInfo[g_curDeviceSel]));
				stu_deviceifo_bak.nDevIdx = -1;
			}
		}
	}
	

	if (1 == nIsOldPrj)
	{

		if (g_curDeviceSel != stu_deviceifo_bak.nDevIdx)
		{
			//不一样才要保存
			memcpy(&stu_deviceifo_bak.deviceinfo, &pstuDevInfo[g_curDeviceSel], sizeof(pstuDevInfo[g_curDeviceSel]));
			stu_deviceifo_bak.nDevIdx = g_curDeviceSel;
		}
		

		memcpy(&pstuDevInfo[g_curDeviceSel], pCurDeviceInfo, sizeof(pstuDevInfo[g_curDeviceSel]));
	}

	return 0;
}
BOOL  CMainFrame::PeekAndPump()
{
	static MSG msg;

	while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
		if (!AfxGetApp()->PumpMessage()) {
			::PostQuitMessage(0);
			return FALSE;
		}
	}

	return TRUE;
}


//#define JXSAVEPRJ

void CMainFrame::OnMenuPrjSave()
{
	
	CString strTmp;
	TCHAR swzTmp[40];


	if (g_curDeviceSel == -1)return;
	
	if (AnyprogRunning(0xFF))
	{
		pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
		return;
	}
	if (stu_ProjectStatus.nIsInPrj == 1)
	{
		strTmp.LoadStringW(IDS_STRIN_SAVEINOLDPRJ);
		if (IDNO == AfxMessageBox(strTmp, MB_YESNO | MB_ICONEXCLAMATION))
		{
			return;
		}
	}

	CString strSavePrjPath;
	CString filter = L"文件 (*.ycpj)|*.ycpj|All Files(*.*)|*.*||";	//文件过虑的类型
	CFileDialog openFileDlg(FALSE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, filter, NULL);
	 if (openFileDlg.DoModal() == IDOK)
	{
		//pFormView2->StartLoadDll();
		 strSavePrjPath = openFileDlg.GetPathName();
		 if (strSavePrjPath.Right(5) !=L".ycpj")
		 {
			 strSavePrjPath += L".ycpj";
		 }
		CProgressBar bar(_T(""), 100, 100, TRUE);

		nStaIdx = 0;
		int nCurAvailPlane = 0;
		int i = 0;
		ULONGLONG llchecksum = 0;

		HANDLE hFile;
		TCHAR wzbuf[MAX_PATH];
		char szBuf[MAX_PATH];
		TCHAR wszFilename[50];

		CString strtmp;
		int nbarsteplen;
		int bRet;


		//载入配置字和INFO的字段，用于直接保存工程。
		CreateDownloadData();
		if (1 == stu_ProjectStatus.nIsInPrj)
		{
			pFormView3->RichEditShowAll(0, L"Saving project in old project setting... ", COLOR_GHOSTWHITE, 0, 0);
		}
		else
		{
			pFormView3->RichEditShowAll(0, L"Saving project... ", COLOR_GHOSTWHITE, 0, 0);
		}
		

		pFormView3->DisplayDeviceBrief();
		//如果是工程中，再保存，就用旧配置，prj//
		ReadAlgo_Fpga_ConfigFromFile2Buf(0, stu_ProjectStatus.nIsInPrj);
#ifdef JXSAVEPRJ
		if (IDYES == nSaveType)
		{
			memcpy(stu_ProjectHead.szMagic, "XCPJ", strlen("XCPJ"));
		}
		else
#endif
		{
			memcpy(stu_ProjectHead.szMagic, "MYPJ", strlen("MYPJ"));
		}
		stu_ProjectHead.nVersion = 1;
		//每次要重新计算，否则，老工程载入错了，下次错误的数值继续代入
		stu_ProjectHead.nHeadLen = sizeof(stu_ProjectHead);
		stu_ProjectHead.nLenStuDeviceInfo = sizeof(STU_DEVICE_INFO);

		stu_ProjectHead.nLenConfigWord_info = sizeof(m_cDownData[0]);
		memcpy(stu_ProjectHead.llCheckSumFile, this->llCheckSumFile, sizeof(this->llCheckSumFile));
		memcpy(stu_ProjectHead.llCheckSumBuf, this->llCheckSumBuf, sizeof(this->llCheckSumBuf));
		stu_ProjectHead.llTotalCheckSumBuf = llTotalCheckSumBuf;
		stu_ProjectHead.llTotalCheckSumFile = llTotalCheckSumFile;
		for (i = 0; i < BUFNUM; i++)
		{
			TcharToChar(stu_ProjectHead.szBufferFilePathArr[i], g_wszFilePathArr[i]);
		
		}
		
		//检查prj里面是否有'p'的选项，没有就要报警提示
		for (i = 0; i < stu_AutoSeqGlob.nAutoCnt; i++)
		{
			if (stu_FuncList.cFuncAttr[stu_AutoSeqGlob.nAutoidxArray[i]] == 'p')
				break;
		}
		//没有找到P选项，要报警提示。
		if (i == stu_AutoSeqGlob.nAutoCnt)
		{
			
			if (IDNO == MessageBox(_T("No program function in prj,Continue?"), _T("Warnning"), MB_YESNO | MB_ICONEXCLAMATION | MB_APPLMODAL))
			{
				return;
			}
			
		}

		CFile prjfile;
		if (!prjfile.Open(strSavePrjPath, CFile::modeCreate | CFile::modeWrite))
		{
			AfxMessageBox(L"mypj.prj open error");
			return;
		}
		//SN数据结构保存
		stu_ProjectHead.stu_GenSetting_prj = stu_GenSetting;	
		for (i = 0; i < PROGRAMERMAXNUM; i++)
		{
			if (stu_UsbDeviceArr[i].status != USBNOTCONNECT)break;

		}
		int origmask = 0xff;
		if (i >= PROGRAMERMAXNUM)
		{
			switch (pstuDevInfo[g_curDeviceSel].unit)
			{
			case 1:
				origmask = 0x1;
				break;
			case 2:
				origmask = 0x3;
				break;
			case 4:
				origmask = 0xf;
				break;
			case 8:
				origmask = 0xff;
				break;
			}
		}
		else
		{
			origmask = stu_UsbDeviceArr[i].curSocketUnit;
		}
		
	
		stu_ProjectHead.nCurUnitSel = origmask;
		stu_ProjectHead.nEraseWhenBLKFail=g_nEraseWhenNOTBlank;
		stu_ProjectHead.nIsIdCheck= g_nIsNeedChkId;
		stu_ProjectHead.nRealFileSize = (UINT)m_ullRealFileSize[0];


		//保存AUTO IDX对应的NAME字符串,只能保存AUTO的FUNCTION  name里的19个字符
		for (i = 0; i < stu_AutoSeqGlob.nAutoCnt; i++)
		{
			pFormView1->GetDlgItem(pFormView1->PROCBTN_ARR[stu_AutoSeqGlob.nAutoidxArray[i]])->GetWindowTextW(swzTmp, sizeof(swzTmp) / sizeof(swzTmp[0]));
			TcharToChar(szBuf, swzTmp);
			if (strlen(szBuf) > 19)szBuf[19] = 0;
			strcpy(stu_ProjectHead.szAutoArrName[i], szBuf);
			if (i == 9)break;
		}
	
		//保存工程时间
		time_t t = time(0);
		

		struct tm newtime;
		localtime_s(&newtime, &t);
		

		//日期
	
		char sztmp[20];
		sztmp[0] = 'T';
		TcharToChar(sztmp+1, g_wszCapTime + 2);
		sztmp[7] = 0;
		strcpy(stu_ProjectHead.szCapTime, sztmp);
		//cap time
		sprintf(stu_ProjectHead.szSaveTime, "V%02d%02d%02d", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday);
		
		//保存文件头
		//INT TTT = prjfile.GetPosition();
		prjfile.Write(&stu_ProjectHead, sizeof(stu_ProjectHead));
	
		llchecksum += CalcCheckSum((PUCHAR)&stu_ProjectHead, sizeof(stu_ProjectHead));
		//保存devece info

		//BUG没有找到，规避的法子，没办法
		if (strcmp(pstuDevInfo[g_curDeviceSel].szJsonFileName,"x.json"))
		{
			AfxMessageBox(L"get xjson==0");
			strcpy(pstuDevInfo[g_curDeviceSel].szJsonFileName, "x.json");
		}
		int nDevInfoPrjAddr = prjfile.GetPosition();
		//emmc 后面还要再写一遍
		prjfile.Write(&pstuDevInfo[g_curDeviceSel], sizeof(STU_DEVICE_INFO));
		

		//llchecksum += CalcCheckSum((PUCHAR)&pstuDevInfo[g_curDeviceSel], sizeof(STU_DEVICE_INFO));
		//保存4B available SNCNT+ 16B SN(CNT)
		int nSNcnt = strListSN.GetCount();
		int nDeSNcnt = nSNcnt;
		decodeSN((char*)&nDeSNcnt, 4);
		llchecksum += CalcCheckSum((PUCHAR)&nDeSNcnt, sizeof(nSNcnt));
		prjfile.Write(&nDeSNcnt, sizeof(nDeSNcnt));
		if (nSNcnt)
		{

			POSITION rPos = strListSN.GetHeadPosition();
			while (rPos != NULL)
			{
				strtmp = strListSN.GetNext(rPos);
				wcscpy_s(wzbuf, strtmp.GetBuffer());
				strtmp.ReleaseBuffer();
				TcharToChar(szBuf, wzbuf);
				decodeSN(szBuf, 16);
				prjfile.Write(szBuf, 16);
				llchecksum += CalcCheckSum((PUCHAR)szBuf, 16);
			}
		}

		//长度由选芯片确定的时候赋值过了
		//保存算法
		prjfile.Write(m_pAlgoData, stu_ProjectHead.nLenAlgo);
		llchecksum += CalcCheckSum((PUCHAR)m_pAlgoData, stu_ProjectHead.nLenAlgo);
		//保存FPGA1,优先保存256，为0，才保存320
		if (strlen(pstuDevInfo[g_curDeviceSel].szFpga0))
		{
			if (stu_ProjectHead.nLenFpga0 == m_nFpga0Len_256)
			{
				prjfile.Write(m_pFpga0Data_256, stu_ProjectHead.nLenFpga0);
				llchecksum += CalcCheckSum((PUCHAR)m_pFpga0Data_256, stu_ProjectHead.nLenFpga0);
			}
			else
			{
				prjfile.Write(m_pFpga0Data_320, stu_ProjectHead.nLenFpga0);
				llchecksum += CalcCheckSum((PUCHAR)m_pFpga0Data_320, stu_ProjectHead.nLenFpga0);

			}
			
			
		}


		//保存fpga2
		if (strlen(pstuDevInfo[g_curDeviceSel].szFpga1))
		{
			if (stu_ProjectHead.nLenFpga1 == m_nFpga1Len_256)
			{
				prjfile.Write(m_pFpga1Data_256, stu_ProjectHead.nLenFpga1);
				llchecksum += CalcCheckSum((PUCHAR)m_pFpga1Data_256, stu_ProjectHead.nLenFpga1);
			}
			else
			{
				prjfile.Write(m_pFpga1Data_320, stu_ProjectHead.nLenFpga1);
				llchecksum += CalcCheckSum((PUCHAR)m_pFpga1Data_320, stu_ProjectHead.nLenFpga1);

			}
		}
		//保存fpga3
		if (strlen(pstuDevInfo[g_curDeviceSel].szFpga2))
		{
			if (stu_ProjectHead.nLenFpga2 == m_nFpga2Len_256)
			{
				prjfile.Write(m_pFpga2Data_256, stu_ProjectHead.nLenFpga2);
				llchecksum += CalcCheckSum((PUCHAR)m_pFpga2Data_256, stu_ProjectHead.nLenFpga2);
			}
			else
			{
				prjfile.Write(m_pFpga2Data_320, stu_ProjectHead.nLenFpga2);
				llchecksum += CalcCheckSum((PUCHAR)m_pFpga2Data_320, stu_ProjectHead.nLenFpga2);

			}
		}
		//保存fpga4
		if (strcmp(pstuDevInfo[g_curDeviceSel].szFpga3, "F_ALLPINHIGHZ") && strcmp(pstuDevInfo[g_curDeviceSel].szFpga3, "F_ALLPINHIGHZ_OF"))
		{
			if (strlen(pstuDevInfo[g_curDeviceSel].szFpga3))
			{
				if (stu_ProjectHead.nLenFpga3 == m_nFpga3Len_256)
				{
					prjfile.Write(m_pFpga3Data_256, stu_ProjectHead.nLenFpga3);
					llchecksum += CalcCheckSum((PUCHAR)m_pFpga3Data_256, stu_ProjectHead.nLenFpga3);
				}
				else
				{
					prjfile.Write(m_pFpga3Data_320, stu_ProjectHead.nLenFpga3);
					llchecksum += CalcCheckSum((PUCHAR)m_pFpga3Data_320, stu_ProjectHead.nLenFpga3);

				}
			}
			
		}
	//保存configfile CONFIG文件。用于恢复。因为CONFIG很可能被改了
			prjfile.Write(m_pConfigFile, stu_ProjectHead.nLenConfigFile);
			llchecksum += CalcCheckSum((PUCHAR)m_pConfigFile, stu_ProjectHead.nLenConfigFile);

		//保存CONFIGWORD+infopara 下发的数据
		prjfile.Write(m_cDownData[0], stu_ProjectHead.nLenConfigWord_info);
		
		
		llchecksum += CalcCheckSum((PUCHAR)m_cDownData[0], stu_ProjectHead.nLenConfigWord_info);
		//保存AUTO STRUCTURE
		prjfile.Write(&stu_AutoSeqGlob, sizeof(stu_AutoSeqGlob));
		llchecksum += CalcCheckSum((PUCHAR)&stu_AutoSeqGlob, sizeof(stu_AutoSeqGlob));
	
		

		//粒度和DLL
		if (m_nIsLoadBufferDll)
		{
			if (m_nIsReadFitnessNeedDataAnalysis)
			{
				CreateDataAnalysis();
				m_nIsReadFitnessNeedDataAnalysis = 0;
			}
		
				pFormView2->StartLoadDll();
				m_nIsLoadBufferDll = 0;
			
		}
		


		//保存 文件内容
		for (i = 0; i < BUFNUM; i++)
		{
			if (strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]) && strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[i]))
			{
				CharToTchar(wszFilename, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);
				//wsprintf(wszFilename, L"buffile%d", i);
				wcscpy_s(wzbuf, g_wszCurPath);
				wcscat(wzbuf, L"lib\\");
				CharToTchar(wzbuf + wcslen(wzbuf), pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);
				wcscat(wzbuf, L".bf");
				hFile = CreateFile(wzbuf,
					GENERIC_READ,//对文件的操作
					0, // 共享的方式 0 不能共享
					NULL,// 安全属性 用缺省的
					OPEN_EXISTING, //
					FILE_ATTRIBUTE_READONLY, // 文件属性
					NULL); // 模板文件的句柄

				if (hFile == INVALID_HANDLE_VALUE)
				{
					strtmp.Format(L"open %s fail", wzbuf);
					AfxMessageBox(strtmp);
					return;
				}
				//filelen=GetFileSize(hFile, NULL);


				LARGE_INTEGER nLGFileSize;
				GetFileSizeEx(hFile, &nLGFileSize);
				LONGLONG llFileSize = nLGFileSize.QuadPart;
				if (pstuDevInfo[g_curDeviceSel].nIsEmmc)
				{
						sprintf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[i], "%I64x", llFileSize);
					
				}
				nbarsteplen = llFileSize / sizeof(gSendbuf) + 1;
				bar.SetRange(0, nbarsteplen);
				DWORD dwReadSize;
				while (1)
				{
					bRet = ReadFile(hFile, gSendbuf, sizeof(gSendbuf), &dwReadSize, NULL);
					if (!bRet)
					{
						CloseHandle(hFile);
						strtmp.Format(L"read %s fail", wzbuf);
						AfxMessageBox(strtmp);
						return;
					}


					prjfile.Write(gSendbuf, dwReadSize);
					llchecksum += CalcCheckSum((PUCHAR)gSendbuf, dwReadSize);
					if (dwReadSize < sizeof(gSendbuf))break;


					bar.StepIt();
					PeekAndPump();


				}
				bar.StepIt();
				PeekAndPump();
				bar.SetPos(nbarsteplen);
				CloseHandle(hFile);


			}
		}
		int ttt = prjfile.GetPosition();
		llchecksum += CalcCheckSum((PUCHAR)&pstuDevInfo[g_curDeviceSel], sizeof(STU_DEVICE_INFO));
		prjfile.Write(&llchecksum, sizeof(llchecksum));
		//DEVINFO 更新后写回
		prjfile.Seek(nDevInfoPrjAddr, CFile64::begin);	
		prjfile.Write(&pstuDevInfo[g_curDeviceSel], sizeof(STU_DEVICE_INFO));

		prjfile.Close();
		bar.Clear();

		
		DisplayBufInfo();
		DispConfigWord(1);
		DispAutoSeq();
		DispGeneralSetting();
		DisplaySocketInfo(stu_ProjectHead.nCurUnitSel);
		pFormView3->RichEditShowAll(0,strSavePrjPath, COLOR_GHOSTWHITE, 0, 0);
		pFormView3->RichEditShowAll(0,L"Save Project OK", COLOR_GHOSTWHITE, 0, 0);
		pFormView3->RichEditShowAll(0,STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
		pFormView3->RichEditShowAll(0,L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);
		pFormView3->RichEditShowAll(0,L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);
	}
	
	
	
}
void CMainFrame::OnMenuFunCancel()
{
	if (g_curDeviceSel == -1)return;
	
	else if (2 == stu_RemoteStat.nRemoteStat)
	{
		pFormView3->RichEditShow(0, L"Forbidden in the mode", COLOR_YELLOW, 0, 0);
		return;
	}
	if (stu_ProjectStatus.nIsInPrj && (m_bIsPrjEditable == 0))
	{
		pFormView3->RichEditShow(0, L"Forbidden in the mode", COLOR_YELLOW, 0, 0);
		return;
	}
	
	if (g_isProgramOnline)
	{
		memset(&stu_AutoSeq, 0, sizeof(stu_AutoSeq));
		if (stu_UsbDeviceArr[0].status == USBCONNECT_RUN)
		{
			m_nAutoCntPressure[0] = 0;
			AfxBeginThread((AFX_THREADPROC)RunCmdCancel0, (LPVOID)this);
		}
		if (stu_UsbDeviceArr[1].status == USBCONNECT_RUN)
		{
			m_nAutoCntPressure[1] = 0;
			AfxBeginThread((AFX_THREADPROC)RunCmdCancel1, (LPVOID)this);
		}
		if (stu_UsbDeviceArr[2].status == USBCONNECT_RUN)
		{
			m_nAutoCntPressure[2] = 0;
			AfxBeginThread((AFX_THREADPROC)RunCmdCancel2, (LPVOID)this);
		}
		if (stu_UsbDeviceArr[3].status == USBCONNECT_RUN)
		{
			m_nAutoCntPressure[3] = 0;
			AfxBeginThread((AFX_THREADPROC)RunCmdCancel3, (LPVOID)this);
		}
		if (stu_UsbDeviceArr[4].status == USBCONNECT_RUN)
		{
			m_nAutoCntPressure[4] = 0;
			AfxBeginThread((AFX_THREADPROC)RunCmdCancel4, (LPVOID)this);
		}
		if (stu_UsbDeviceArr[5].status == USBCONNECT_RUN)
		{
			m_nAutoCntPressure[5] = 0;
			AfxBeginThread((AFX_THREADPROC)RunCmdCancel5, (LPVOID)this);
		}
		if (stu_UsbDeviceArr[6].status == USBCONNECT_RUN)
		{
			m_nAutoCntPressure[6] = 0;
			AfxBeginThread((AFX_THREADPROC)RunCmdCancel6, (LPVOID)this);
		}
		if (stu_UsbDeviceArr[7].status == USBCONNECT_RUN)
		{
			m_nAutoCntPressure[7] = 0;
			AfxBeginThread((AFX_THREADPROC)RunCmdCancel7, (LPVOID)this);
		}
		if (stu_UsbDeviceArr[8].status == USBCONNECT_RUN)
		{
			m_nAutoCntPressure[8] = 0;
			AfxBeginThread((AFX_THREADPROC)RunCmdCancel8, (LPVOID)this);
		}
		if (stu_UsbDeviceArr[9].status == USBCONNECT_RUN)
		{
			m_nAutoCntPressure[9] = 0;
			AfxBeginThread((AFX_THREADPROC)RunCmdCancel9, (LPVOID)this);
		}
	}
	
}
void CMainFrame::CancelSingle(int nProgIdx)
{
	if (g_curDeviceSel == -1)return;
	if (g_isProgramOnline)
	{
		memset(&stu_AutoSeq[nProgIdx], 0, sizeof(stu_AutoSeq[nProgIdx]));
		switch (nProgIdx)
		{
			case 0:
				if (stu_UsbDeviceArr[0].status == USBCONNECT_RUN)
				{
					AfxBeginThread((AFX_THREADPROC)RunCmdCancel0, (LPVOID)this);
					
				}
				break;
			case 1:
				if (stu_UsbDeviceArr[1].status == USBCONNECT_RUN)
				{
					AfxBeginThread((AFX_THREADPROC)RunCmdCancel1, (LPVOID)this);
				}
				break;
			case 2:
				if (stu_UsbDeviceArr[2].status == USBCONNECT_RUN)
				{
					AfxBeginThread((AFX_THREADPROC)RunCmdCancel2, (LPVOID)this);
				}
				break;
			case 3:
				if (stu_UsbDeviceArr[3].status == USBCONNECT_RUN)
				{
					AfxBeginThread((AFX_THREADPROC)RunCmdCancel3, (LPVOID)this);
				}
			case 4:
				if (stu_UsbDeviceArr[4].status == USBCONNECT_RUN)
				{
					AfxBeginThread((AFX_THREADPROC)RunCmdCancel4, (LPVOID)this);
				}
			case 5:
				if (stu_UsbDeviceArr[5].status == USBCONNECT_RUN)
				{
					AfxBeginThread((AFX_THREADPROC)RunCmdCancel5, (LPVOID)this);
				}
				break;
		}
		
		
		
		
	}
}
//保存算法，FPGA0,1到内存
long long CMainFrame::ReadAlgoFpgaConfigToBuffer(char* pBuf,char *szFilepath,int nIsFPGA,char *pBuf_F256,int nIsOldPrj)
{
	int i=0,j;
	HANDLE hFile;
	INT nIsF320 = 0 , nIsF256 = 0;
	long long filelen=0,bRet;
	long long ret=0;
		TCHAR wzbuf[MAX_PATH];
		TCHAR wzbufbac[MAX_PATH];
		TCHAR wszFilename[50];

		CString strtmp;
		CharToTchar(wszFilename, szFilepath);
		wcscpy_s(wzbuf, g_wszCurPath);
		
		wcscat(wzbuf, L"lib\\");
		
		for (j = 0; j < g_nCustomerDefProgCnt; j++)
		{
			if (stu_UsbDeviceArr[j].status != USBNOTCONNECT)
			{
				if (stu_UsbDeviceArr[j].cIsFPGA256)
				{
					nIsF256 = 1;
				}
				else
				{
					nIsF320 = 1;
				}
				
			}
		}
		if((0==nIsF256)&&(0 == nIsF320))nIsF256 = 1;
		if (nIsOldPrj)
		{
			wcscat_s(wzbuf, L"prj\\");
		}

		wcscpy(wzbufbac, wzbuf);
		if (nIsFPGA)
		{	
			if (nIsF320)
			{
				wcscat(wzbuf, L"F3\\");
		
				wcscat(wzbuf, wszFilename);
		
				hFile = CreateFile(wzbuf,
				GENERIC_READ,//对文件的操作
				0 , // 共享的方式 0 不能共享
				NULL,// 安全属性 用缺省的
				OPEN_EXISTING, //
				FILE_ATTRIBUTE_READONLY, // 文件属性
				NULL); // 模板文件的句柄

				if (hFile == INVALID_HANDLE_VALUE)
				{
				strtmp.Format(L"open %s fail", wzbuf);
				AfxMessageBox(strtmp);
				return -1;
				}
				filelen=GetFileSize(hFile, NULL);
				char *pContent = pBuf;
	

				DWORD dwReadSize = 0;
				bRet = ReadFile(hFile, pContent, filelen, &dwReadSize, NULL);
				if (!bRet)
				{
					CloseHandle(hFile);
					
					strtmp.Format(L"read %s fail", wzbuf);
					pFormView3->RichEditShow(0, strtmp, COLOR_RED, 0, 0);
					AfxMessageBox(strtmp);
					return -1;
				}
				CloseHandle(hFile);
				ret=filelen;
			}
	
		
			if (nIsF256)
			{
				wcscpy(wzbuf, wzbufbac);
				wcscat(wzbuf, L"F2\\");
				wcscat(wzbuf, wszFilename);

				hFile = CreateFile(wzbuf,
					GENERIC_READ,//对文件的操作
					0, // 共享的方式 0 不能共享
					NULL,// 安全属性 用缺省的
					OPEN_EXISTING, //
					FILE_ATTRIBUTE_READONLY, // 文件属性
					NULL); // 模板文件的句柄

				if (hFile == INVALID_HANDLE_VALUE)
				{
					strtmp.Format(L"open %s fail", wzbuf);
					pFormView3->RichEditShow(0, strtmp, COLOR_RED, 0, 0);
					AfxMessageBox(strtmp);
					return -1;
				}
				filelen = GetFileSize(hFile, NULL);
				char *pContent = pBuf_F256;


				DWORD dwReadSize = 0;
				bRet = ReadFile(hFile, pContent, filelen, &dwReadSize, NULL);
				if (!bRet)
				{
					CloseHandle(hFile);
					strtmp.Format(L"read %s fail", wzbuf);
					pFormView3->RichEditShow(0, strtmp, COLOR_RED, 0, 0);
					AfxMessageBox(strtmp);
					return -1;
				}
				CloseHandle(hFile);
				//ret = filelen;
				ret|=(filelen<<32);
			}

		}
		else
		{
			wcscat(wzbuf, wszFilename);

			hFile = CreateFile(wzbuf,
				GENERIC_READ,//对文件的操作
				0, // 共享的方式 0 不能共享
				NULL,// 安全属性 用缺省的
				OPEN_EXISTING, //
				FILE_ATTRIBUTE_READONLY, // 文件属性
				NULL); // 模板文件的句柄

			if (hFile == INVALID_HANDLE_VALUE)
			{
				strtmp.Format(L"open %s fail", wzbuf);
				pFormView3->RichEditShow(0, strtmp, COLOR_RED, 0, 0);
				AfxMessageBox(strtmp);
				return -1;
			}
			filelen = GetFileSize(hFile, NULL);
			char *pContent = pBuf;


			DWORD dwReadSize = 0;
			bRet = ReadFile(hFile, pContent, filelen, &dwReadSize, NULL);
			if (!bRet)
			{
				CloseHandle(hFile);
				strtmp.Format(L"read %s fail", wzbuf);
				pFormView3->RichEditShow(0, strtmp, COLOR_RED, 0, 0);
				AfxMessageBox(strtmp);
				return -1;
			}
			CloseHandle(hFile);
			ret=filelen;
		}


	

	


	return ret;

}
int CMainFrame::ReadAlgo_Fpga_ConfigFromFile2Buf(int updateFunclist,int nIsOldPrj)
{
	
	TCHAR wszTemp[MAX_PATH];
	char szTemp[MAX_PATH];
	int i,j;
	CString strTime;
	
	long long  llLen;
	char *pBuf = NULL;
	llLen = ReadAlgoFpgaConfigToBuffer(m_pAlgoData, pstuDevInfo[g_curDeviceSel].szAlgo, 0,NULL, nIsOldPrj);
	if (-1 == llLen)return -1;
	CharToTchar(wszTemp, pstuDevInfo[g_curDeviceSel].szAlgo);
	if (updateFunclist)
	{
		GetFileModifyTime(strTime, wszTemp);
		m_strC_F_FileModifyTime.Format(L"C(%s)", strTime);
	}
	
	
	stu_ProjectHead.nLenAlgo = m_nAlgoLen = llLen;
	
	//m_pAlgoData = pBuf;
	//要显示FUNC LIST按钮
	if (updateFunclist)
	{
		for (i = 0; i < BUTTONCNT; i++)
		{
			pFormView1->m_ProcBtn[i].SetWindowText(L"");
			pFormView1->m_ProcBtn[i].ShowWindow(0);
		}
		int offset = llLen - sizeof(stu_FuncList.szFunListArr) - sizeof(stu_FuncList.cFuncAttr);
		//32个
		for (i = 0; i < sizeof(stu_FuncList.szFunListArr) / sizeof(stu_FuncList.szFunListArr[0]); i++)
		{
			memcpy(&stu_FuncList.szFunListArr[i], m_pAlgoData + offset, sizeof(stu_FuncList.szFunListArr[i]));
			offset += sizeof(stu_FuncList.szFunListArr[i]);
			memcpy(&stu_FuncList.cFuncAttr[i], m_pAlgoData + offset, sizeof(stu_FuncList.cFuncAttr[i]));
			offset += sizeof(stu_FuncList.cFuncAttr[i]);
		}
			
		i = 0;
		while (1)
		{
			//funlist到末尾了。
			if (0 == stu_FuncList.szFunListArr[i][0])
			{
				stu_FuncList.nAutoCnt = i;
				break;
			}
			//左侧BUTTON赋值
			if (strlen(stu_FuncList.szFunListArr[i]) > 23)
			{
				CharToTchar(wszTemp, stu_FuncList.szFunListArr[i]);
				wcscat(wszTemp, L" ");
				wcscat(wszTemp, L"操作项目务必小于23个字符");
				AfxMessageBox(wszTemp);
			//	stu_FuncList.szFunListArr[i][20] = 0;
			}
			CharToTchar(wszTemp, stu_FuncList.szFunListArr[i]);
			pFormView1->m_ProcBtn[i].ShowWindow(1);
			
			pFormView1->m_ProcBtn[i].SetWindowText(wszTemp);
			i++;
		}
		//stu_ProjectHead.nLenAlgo = m_nAlgoLen = llLen - sizeof(stu_FuncList.szFunListArr);
		m_nAlgoLen = llLen - sizeof(stu_FuncList.szFunListArr);
	}
		

	
	if (strlen(pstuDevInfo[g_curDeviceSel].szFpga0))
	{
		llLen = ReadAlgoFpgaConfigToBuffer(m_pFpga0Data_320, pstuDevInfo[g_curDeviceSel].szFpga0, 1, m_pFpga0Data_256, nIsOldPrj);
		if (-1 == llLen)return -21;
		m_nFpga0Len_256 = llLen >> 32;
		m_nFpga0Len_320 = (int)llLen;
		CharToTchar(wszTemp, pstuDevInfo[g_curDeviceSel].szFpga0);
		if(m_nFpga0Len_256)
			stu_ProjectHead.nLenFpga0 = m_nFpga0Len_256 ;
		else
			stu_ProjectHead.nLenFpga0 = m_nFpga0Len_320;
		GetFileModifyTime(strTime, wszTemp);
		m_strC_F_FileModifyTime.AppendFormat(L",F0(%s)", strTime);
	}
	else
	{
		stu_ProjectHead.nLenFpga0 = m_nFpga0Len_320 = 0;
	}
	if (strlen(pstuDevInfo[g_curDeviceSel].szFpga1))
	{
		llLen = ReadAlgoFpgaConfigToBuffer(m_pFpga1Data_320, pstuDevInfo[g_curDeviceSel].szFpga1, 1, m_pFpga1Data_256, nIsOldPrj);
		if (-1 == llLen)return -22;
		m_nFpga1Len_256 = llLen >> 32;
		m_nFpga1Len_320 = (int)llLen;
		if (m_nFpga1Len_256)
			stu_ProjectHead.nLenFpga1 = m_nFpga1Len_256;
		else
			stu_ProjectHead.nLenFpga1 = m_nFpga1Len_320;
		CharToTchar(wszTemp, pstuDevInfo[g_curDeviceSel].szFpga0);
		GetFileModifyTime(strTime, wszTemp);
		m_strC_F_FileModifyTime.AppendFormat(L",F1(%s)", strTime);
	}
	else
	{
		stu_ProjectHead.nLenFpga1 = m_nFpga1Len_320 = 0;
	}
	if (strlen(pstuDevInfo[g_curDeviceSel].szFpga2))
	{
		llLen = ReadAlgoFpgaConfigToBuffer(m_pFpga2Data_320, pstuDevInfo[g_curDeviceSel].szFpga2, 1, m_pFpga2Data_256, nIsOldPrj);
		if (-1 == llLen)return -23;
		m_nFpga2Len_320 = (int)llLen;
		m_nFpga2Len_256 = llLen >> 32;
		if (m_nFpga2Len_256)
			stu_ProjectHead.nLenFpga2 = m_nFpga2Len_256;
		else
			stu_ProjectHead.nLenFpga2 = m_nFpga2Len_320;
		
	}
	else
	{
		stu_ProjectHead.nLenFpga2 = m_nFpga2Len_320 = 0;
	}
	if (strlen(pstuDevInfo[g_curDeviceSel].szFpga3))
	{
		llLen = ReadAlgoFpgaConfigToBuffer(m_pFpga3Data_320, pstuDevInfo[g_curDeviceSel].szFpga3, 1, m_pFpga3Data_256, nIsOldPrj);
		if (-1 == llLen)return -24;
		m_nFpga3Len_320 = (int)llLen;
		m_nFpga3Len_256 = llLen >> 32;
		if (m_nFpga3Len_256)
			stu_ProjectHead.nLenFpga3 = m_nFpga3Len_256;
		else
			stu_ProjectHead.nLenFpga3 = m_nFpga3Len_320;
	}
	else
	{
		stu_ProjectHead.nLenFpga3 = m_nFpga3Len_320 = 0;
	}
	strcpy_s(szTemp, pstuDevInfo[g_curDeviceSel].szConfig);
	
	if (0 == strcmp(szTemp, ""))
	{
		strcpy(szTemp, "C_DUMMY");
	}
	llLen = ReadAlgoFpgaConfigToBuffer(m_pConfigFile, szTemp, 0,NULL, nIsOldPrj);
	if (-1 == llLen)return -3;
	
	stu_ProjectHead.nLenConfigFile = llLen;
		
	
}
void CMainFrame::OnMenuFun2()
{
#ifdef SPVERSION
	CDeviceSelectDialog devseldlg;
	devseldlg.DeviceSelect(0);
#endif
	SelectDevice(0,NULL,NULL,NULL,NULL);
}

int CMainFrame::SelectDevice(int nType,CString strMan,CString strDev,CString strPackage,CString strISP)
{
	CString strTmp=g_wszCurPath,strTmp_= g_wszCurPath;
	TCHAR *pswzTemp;
	int nAvailableProCnt = 0;
	int nNowOneAvailable = 0;
	TCHAR wszTemp[MAX_PATH], wszTemp1[MAX_PATH];
	
	CHAR szTemp[MAX_PATH], szSN[MAX_PATH], szSNOut[1024];
	int i = 0, l = 0, j;
	int ret = 0,dlgret=-1;

	//FPGA256,320不能共存
	ret = 0; j = 0; i = 0;
	if (AnyprogRunning(0xFF))
	{
		pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
		return -1;
	}

#ifdef SPVERSION
	
	//CDeviceSelectDialog devseldlg;
	if (0 == nType)
	{
	
	

		
		strTmp += L"lib\\devl";
		strTmp_ = strTmp + L"_";
		DecodeXor(strTmp_, strTmp);
		TcharToChar(szTemp, strTmp_.GetBuffer());

		strTmp = g_wszCurPath;
		strTmp += _T("qtdialog.dll");

		HMODULE hdll = ::LoadLibrary(strTmp);

		DWORD errorCode = GetLastError();  // get the last error code
		TCHAR errorMsg[256] = { 0 };        // create a buffer to store the error message
		// format the error code into a readable error message
		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			errorMsg, (sizeof(errorMsg) / sizeof(TCHAR)), NULL);
		if (errorCode)
		{
			// print the error message
			strTmp.Format(L"Failed to open file: Error code %d: %s\n", errorCode, errorMsg);
		}

		szSN[0] = 0;
		if (hdll != NULL)
		{
			for (i = 0; i < PROGRAMERMAXNUM; i++)
			{
				if (USBNOTCONNECT != stu_UsbDeviceArr[i].status)
				{
					strcat(szSN, stu_UsbDeviceArr[i].serialNO);
					strcat(szSN,",");
				}

			}

			typedef int(*pSelectDevice)(HWND parent, STU_DEVICE_INFO* pStuDevInfoIn, STU_SKT_NAME* pStuSktNameClr, char* szDevFilePathIn, char* szCurSNIn, char* szAvailableSNOut, int *pNCheckcode,int nISPIn,int nIsShowAll);

			pSelectDevice fSelectDevice = pSelectDevice(GetProcAddress(hdll, "showDialog"));
			if (fSelectDevice != NULL)
			{
				
#ifdef ONLINE
				dlgret= fSelectDevice(this->GetSafeHwnd(), pstuDevInfo, pstusktname, szTemp, szSN, szSNOut, &m_nChecksumType, 1, m_nCYJPSD);
				if (-1 != dlgret)
				{
					g_curDeviceSel = dlgret;
				}
				
				if (szSNOut)
				{
					strListSN.RemoveAll();
					
					l = strlen(szSNOut);
					for (i = 0; i < l / 17; i++)
					{
						memcpy(szTemp, &szSNOut[i * 17], 16);
						szTemp[16] = 0;
						CharToTchar(wszTemp, szTemp);
						strListSN.AddTail(wszTemp);
					}
				}
				

#else
				dlgret = fSelectDevice(this->GetSafeHwnd(), pstuDevInfo, pstusktname, szTemp, szSN, szSNOut, &m_nChecksumType, 0, 1);
				if (-1 != dlgret)
				{
					g_curDeviceSel = dlgret;
				}
				
#endif
				if (-1 == dlgret)ret = IDCANCEL;
				else ret = IDOK;

				FreeLibrary(hdll);
				//初始化ADAPT NEAR LIMIT弹框计数
				for (i = 0; i < PROGRAMERMAXNUM; i++)
				{
					m_strSktNearLmt[i].Empty();
				}
				memset(&stu_AdptNearLmtDlgTime, 0, sizeof(stu_AdptNearLmtDlgTime));
			}
			else
			{
				FreeLibrary(hdll);
				return -1;
			}
			
	}
		
	}
	else
	{
		CDeviceSelectDialog devseldlg;
	//	devseldlg.DeviceSelect(0);
		ret=devseldlg.ChooseDeviceDirectly(strMan, strDev, strPackage, strISP);
		if (-1 == ret)
		{
			return ret;
		}
		ret = IDOK;
	}
	
	
#else
	CPropSheetSetting propSheetSetting(L"Setting");
	pSettingSheet = &propSheetSetting;
	//没有应用按钮
	propSheetSetting.m_psh.dwFlags |= PSH_NOAPPLYNOW;
	
	ret = propSheetSetting.DoModal();
#endif
	if (IDOK == ret)
	{

		if (-1 == (CreateEmptyBuffer(0XFF, pstuDevInfo[g_curDeviceSel])))
		{
			pFormView3->RichEditShow(0, L"Create Buffer Fail\n", COLOR_RED, 0, 0);
		}

		CtrlIDDef();
		//curSocketUnit必须给所有的PROG复制，因为剩余的stu_UsbDeviceArr都有可能被插拔征用。那时候如果
		//curSocketUnit是0,那么就不会显示绿色LED
		pFormView2->IconInit();
		for (i = 0; i < PROGRAMERMAXNUM; i++)
		{
			
			stu_UsbDeviceArr[i].curSocketUnit = 0;
			for (l = 0; l < pstuDevInfo[g_curDeviceSel].unit; l++)
			{
				stu_UsbDeviceArr[i].curSocketUnit |= (1 << l);
			}
			g_nSocketUnit[i] = stu_UsbDeviceArr[i].curSocketUnit;
			//统计为0
			
		}
	
		
		memset(g_wszFilePathArr, 0, sizeof(g_wszFilePathArr));
		//获得json内的vcc 和VIO，复制到副本，用于修改保存
		memcpy(m_szVCC, pstuDevInfo[g_curDeviceSel].szVccs, sizeof(pstuDevInfo[g_curDeviceSel].szVccs));
		memcpy(m_szVIO, pstuDevInfo[g_curDeviceSel].szVccIOs, sizeof(pstuDevInfo[g_curDeviceSel].szVccIOs));


		llTotalCheckSumFile = 0;
		llTotalCheckSumBuf = 0;
		memset(llCheckSumFile, 0, sizeof(llCheckSumFile));
		memset(llCheckSumBuf, 0, sizeof(llCheckSumBuf));
		memset(m_ullRealFileSize, 0, sizeof(m_ullRealFileSize));
		memset(g_wszFilePathArr, 0, sizeof(g_wszFilePathArr));


#ifdef SPVERSION
		pFormView3->RichEditShowAll(0,STR_DEVICESELECTSEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
		if (nType)
		{
//			if (devseldlg.m_nRet == -1)
			{
	//			return -1;
			}
		}
#else
		if (propSheetSetting.m_nRet == -1)
		{
			return -1;
		}
#endif
		//如果不是16个SOCKET，连接机子不能超过6个
		if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit < 16))
		{
			if (g_nCustomerDefProgCnt>6)
			{
				g_nCustomerDefProgCnt = 6;
			}
		}


		//不在工程里
#ifdef SPVERSION
		wcscpy_s(wszTemp, g_wszCurPath);
		wcscat(wszTemp, L"lib\\");
		wcscat(wszTemp, L"x.json");

		wcscpy_s(wszTemp1, wszTemp);
		wcscat(wszTemp1, L"_");

		DecodeXor(wszTemp1, wszTemp);

		ReadJson(wszTemp1);//DEVICE SELECT
		DeleteFile(wszTemp1);
#endif
		stu_ProjectStatus.nIsInPrj = 0;
	


		//加载configword from configword.con
		wcscpy_s(wszTemp, g_wszCurPath);
		wcscat_s(wszTemp, L"lib\\");
		if (0 == strcmp("", pstuDevInfo[g_curDeviceSel].szConfig))
		{
			//没有CONFIG，用默认的
			strcpy(pstuDevInfo[g_curDeviceSel].szConfig, "C_DUMMY");

		}
		CharToTchar(wszTemp + wcslen(wszTemp), pstuDevInfo[g_curDeviceSel].szConfig);
		//wcscat_s(wszTemp, L".cf");
		if(-1 == GetConfigFromFile(wszTemp, NULL))
		{
			strTmp.Format(L"Read %s Fail", wszTemp);

			return -1;
		}
		//必须设为0，否则FUNCLIST显示会乱
			pFormView1->m_tabCtrl.SetCurSel(0);
		//当前选中的programmer，SOCKET MAST赋值
			if (-1 == ReadAlgo_Fpga_ConfigFromFile2Buf(1,0))return -1;
			


		for (i = 0; i < PROGRAMERMAXNUM; i++)
		{
			stu_AutoSeq[i].nAutoCnt = pstuDevInfo[g_curDeviceSel].wDftAutCnt;
			stu_AutoSeq[i].nAutoidxArray[i] = pstuDevInfo[g_curDeviceSel].cDftAutCntArr[i];
		}
		stu_AutoSeqGlob.nAutoCnt = pstuDevInfo[g_curDeviceSel].wDftAutCnt;
	//8位8位的取，最多20X4=80个AUTO
		for (i = 0; i < stu_AutoSeqGlob.nAutoCnt; i++)
		{
			if (i < 16)
			{
				stu_AutoSeqGlob.nAutoidxArray[i] = pstuDevInfo[g_curDeviceSel].cDftAutCntArr[i];
			}
			
			else 
			{
				stu_AutoSeqGlob.nAutoidxArray[i] = pstuDevInfo[g_curDeviceSel].cDftAutCntArr1[i-16];
			}
			
		}
		//	memcpy(stu_AutoSeqGlob.nAutoidxArray, propSheetSetting.page2.m_nDftAutoArr, pstuDevInfo[g_curDeviceSel].wDftAutCnt * 4);
#ifndef SPVERSION
		propSheetSetting.page1.SaveJson();
		if (-1 == ReadJson(g_strCurJsonPath))
		{
			//读json失败
			pFormView3->RichEditShow(0, L"READ JSON FAIL", COLOR_RED, CFE_BOLD, 0);
			return -1;
		}

	
	
#endif

		//获得SocketNameFromClrName
#ifdef SPVERSION
		for (i = 0; i < 4; i++)
		{
			//SOCKET CLEAR NAME 有，socket name无，要获得socket name from clear name
			if ((strlen(pstusktname[g_curDeviceSel].szSocketNameClear[i])) && (0 == strlen(pstuDevInfo[g_curDeviceSel].szSocketName[i])))
			{
				//	int nnn = CSktNMMap1.GetCount();
				//	for (j = 0; j < CSktNMMap1.GetCount(); j++)
				{
					CharToTchar(wszTemp, pstusktname[g_curDeviceSel].szSocketNameClear[i]);
					CSktNMMap1.Lookup(wszTemp, strTmp);

					pswzTemp = strTmp.GetBuffer();
					TcharToChar(szTemp, pswzTemp);
					strTmp.ReleaseBuffer();
					strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[i], szTemp);
				}
			}
		}



		//getSocketNameFromClrName  end
		//如果是ISP，并且getSocketNameFromClrName 是空，就不限次数
		if (pstuDevInfo[g_curDeviceSel].isIsp
			&& (0 == strlen(pstusktname[g_curDeviceSel].szSocketNameClear[0]))
			&& (0 == strlen(pstusktname[g_curDeviceSel].szSocketNameClear[1]))
			&& (0 == strlen(pstusktname[g_curDeviceSel].szSocketNameClear[2]))
			&& (0 == strlen(pstusktname[g_curDeviceSel].szSocketNameClear[3])))
		{
			strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], "LFFF");
		}
		if ((strlen(pstuDevInfo[g_curDeviceSel].szSocketName[0]) == 0)
			&& (strlen(pstuDevInfo[g_curDeviceSel].szSocketName[1]) == 0)
			&& (strlen(pstuDevInfo[g_curDeviceSel].szSocketName[2]) == 0)
			&& (strlen(pstuDevInfo[g_curDeviceSel].szSocketName[3]) == 0))
		{
			AfxMessageBox(L"find no Socket Name");
			
			return -1;
		}
#endif


		//芯片选择的LOG目录下的LOG路径初始化
		TCHAR wszTemp1[40];
		time_t t = time(0);
		struct tm newtime;
		localtime_s(&newtime, &t);

		wsprintf(wszTemp1, L"-%02d%02d%02d", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday);

		//获得按照芯片选择保存LOG的文件名。芯片名称+日期+时间
		CharToTchar(wszTemp, pstuDevInfo[g_curDeviceSel].szDeviceName);
		wcscat(wszTemp, wszTemp1);
		wsprintf(wszTemp1, L"%02d%02d%02d", newtime.tm_hour, newtime.tm_min, newtime.tm_sec);
		wcscat(wszTemp, wszTemp1);
		m_strChipSel_PrjName = wszTemp;
		//芯片选择
		m_nChipSel_Prj = INCHIPSEL;


		//根据当前器件的UNIT显示
#if 1
		if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		{
			pFormView2->ShowProgPanel16();
		}
		else
		{
			pFormView2->ShowProgPanel();
		}

		for (i = 0; i < g_nCustomerDefProgCnt; i++)
		{
			//计数显示初始赋值IDC_MODULE1_ICO14IDC_MODULE1_ICO14
			pFormView1->CntDisplayEachLeftListCtrl(i, 1);
			pFormView2->ChkDisplayEachPanel(i, 0xfF, stu_UsbDeviceArr[i].curSocketUnit);
		}
		pFormView1->DisplayDeviceBrief(pstuDevInfo[g_curDeviceSel]);
#endif
		//		pFormView3->DisplayDeviceBrief();
		//激活TABCTRL的第1个PAGE。BUTTONLIST
		pFormView1->m_tabCtrl.SetCurSel(0);
		//触发tabctrl按钮事件，激活第一个PAGE
		NMHDR nh;
		nh.hwndFrom = pFormView1->m_tabCtrl.m_hWnd;
		nh.idFrom = IDC_TAB1;
		nh.code = TCN_SELCHANGE;
		pFormView1->SendMessage(WM_NOTIFY, nh.idFrom, (LPARAM)&nh);


		pFormView2->DispAllBufListCtrl(pstuDevInfo[g_curDeviceSel]);

		if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		{
			pFormView2->AutoPosition16();
		}
		else
		{
			pFormView2->AutoPosition();
		}
		//pFormView2->AutoPosition16();
		//pFormView2->m_FileListCtrl.DeleteAllItems();
		//memset(&stu_AutoSeqGlob, 0, sizeof(stu_AutoSeqGlob));

		m_bIsPrjEditable = TRUE;
		//判断是否有粒度,准备分析
		//	if (pstuDevInfo[g_curDeviceSel].nFitNess)
		//	{
		m_nIsLoadBufferDll = 1;
		/*	}
		else
		{
		m_nIsLoadBufferDll = 0;
		}*/
		g_nIsEmmc = pstuDevInfo[g_curDeviceSel].nIsEmmc;

		stu_BlkTbl.nLen = 0;
		stu_BlkTbl.pData = NULL;
		//没载入文件
		m_nIsDataLoaded = 0;
		for (i = 0; i < PROGRAMERMAXNUM; i++)
		{
			if (stu_UsbDeviceArr[i].status != USBNOTCONNECT)
			{
				g_SerialResBuf[m_nSiteNo[i] - 1] = SER_PROG_READY;
				nNowOneAvailable = i;
				nAvailableProCnt++;
			}
		}


		//help是否有效
		if (0 == strlen(pstuDevInfo[g_curDeviceSel].szHelpName))
		{

			SetBtnSatate(0);
		}
		else
		{
			SetBtnSatate(1);
		}


		stu_GenSetting.nCnt = 0;
		pFormView2->DispAllKeyListCtrl();
#ifdef SNPROGRAM
		pFormView2->readNameTable();
		pFormView2->GetDlgItem(IDC_STATIC_SN1)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_STATIC_SN2)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_STATIC_SN3)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_EDIT_PROGRAMSN)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_EDIT_SOCKETSN)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_EDIT_SOCKETSNCLR)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_EDIT_BOARDSN)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_EDIT_SOCKETLIMIT)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_EDIT_SOCKETCNT)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_STATIC_SKTGRP)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_STATIC_SKTGRP2)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_STATIC_SKTGRP3)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_STATIC54)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_STATIC55)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_STATIC56)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_STATIC57)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_STATIC_SN4)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_EDIT_SOCKETUNICSN)->ShowWindow(1);
		pFormView2->GetDlgItem(IDC_STATIC_SN5)->ShowWindow(1);

#ifdef FPGA256
		pFormView2->m_Banner.ShowWindow(1);
#endif 
#endif


		
		pFormView3->DisplayDeviceBrief();
		DispSocketStatSum();
		//pFormView3->RichEditShow(0, STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);

		//显示配置字
		DispConfigWord(1);
		DispAutoSeq();
		DispGeneralSetting();

		pFormView3->RichEditShowAll(0,L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);
		pFormView3->RichEditShowAll(0,L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);

		CMenu *pMenu = AfxGetMainWnd()->GetMenu();		//主菜单指针
		CMenu *pFileMenu = pMenu->GetSubMenu(3);		//“帮助”菜单指针

		memset(&stu_GenSetting, 0, sizeof(stu_GenSetting));
		//默认删除KEY
		stu_GenSetting.nIsDelete = 1;
		pFileMenu->EnableMenuItem(ID_MENU_DEVICELIST, MF_BYCOMMAND | MF_ENABLED);
		//开发用机子测试SP版本不写机器号
		m_nRDskipSokEncSN = 0;
		if (nAvailableProCnt == 1)
		{
			for (i = 0; i < 20; i++)
			{
				if (0 == strcmp(m_szSkipSokEncSN[i], stu_UsbDeviceArr[nNowOneAvailable].serialNO))
				{
					pFormView3->RichEditShow(0, L"研发用机", COLOR_YELLOW, 0, 6);

					m_nRDskipSokEncSN = 1;
					break;
				}
			}


		}
		//EMMC,读文件路径=载入文件路径
		if ((g_curDeviceSel != -1) && pstuDevInfo[g_curDeviceSel].nIsEmmc)
		{
			for (i = 0; i < BUFNUM; i++)
			{

				strTmp.Format(L"%slib\\", g_wszCurPath);
				CharToTchar(wszTemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);

				strTmp += wszTemp;
				strTmp += L".bf";
				m_strReadFileDefaultPath[i] = strTmp;
			}
		}
		//初始化BUFFER NAME的显示
		int nIdx = 0;
		if (g_curDeviceSel != -1)
		{
			for (i = 0; i < BUFNUM; i++)
			{
				if (strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]) && strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[i]))
				{
					if (pstuDevInfo[g_curDeviceSel].cIsBufferHide[i] == 0)
					{
						m_cComboBufSelMap[nIdx++] = i;
					}
				}
			}
		}
		for (i = 0; i < PROGRAMERMAXNUM; i++)
		{
			//统计为0
			memset(stu_UsbDeviceArr[i].nSokFailCnt, 0, sizeof(stu_UsbDeviceArr[i].nSokFailCnt));
			memset(stu_UsbDeviceArr[i].nSokTotalCnt, 0, sizeof(stu_UsbDeviceArr[i].nSokTotalCnt));
			stu_UsbDeviceArr[i].nTotalFailCnt = 0;
			stu_UsbDeviceArr[i].nTotalCnt = 0;
		}
		pFormView1->DisplayDeviceInfoInleft();
		g_nIsNeedChkId = 1;
#ifdef SPVERSION
		if (0 == nType)
		{
			OnMenuHelp();
		}
	
#endif
	}
	if (50==g_nDebugValue)
	{
		if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		{
			CWnd* hwnd = FindWindow(NULL, L"SetBalls");
			if (hwnd == NULL)
			{
				if (m_dllhandleConnectDlg)
				{
					typedef bool(*callback)(HWND, int, int, char*);
					callback show = (callback)(GetProcAddress(m_dllhandleConnectDlg, "showBalls"));

					// TODO: 在此添加控件通知处理程序代码

					HWND HD = GetSafeHwnd();
					char* color("green");
					show(HD, 29, 2, color);

					//FreeLibrary(dllHandle);
				}
			}
		}
	
		
	}
	
	return 0;
}
void CMainFrame::OnMenuFun4()
{
	if (g_curDeviceSel == -1)return;
	if (AnyprogRunning(0xFF))
	{
		pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
		return;
	}
	INT ret = pFormView2->DoConfigWord();
	if (IDOK == ret)
	{
		DispConfigWord(1);
	}
}
void CMainFrame::OnSize(UINT nType, int cx, int cy)
{
	CRect rect;
	CFrameWnd::OnSize(nType, cx, cy);

	// TODO:  在此处添加消息处理程序代码

	if (m_bCreateClient)
	{
		GetClientRect(&rect);

		int x = rect.Width();

		int y = rect.Height();

		//m_wndSplitter.MoveWindow(-2, -2, x, y + 3);

		m_wndSplitter.SetColumnInfo(0, (x / 6), 0); //左边窗格位置

		m_wndSplitter.SetColumnInfo(1, (x / 10) * 5, 0); //右边窗格位置

		m_wndSplitter.SetColumnInfo(2, (x / 10)*5+30, 0); //右边窗格位置
		m_wndSplitter.RecalcLayout();

		static int cnt = 0;
		CString ss;
		ss.Format(L"%d", cnt++);
		pFormView2->GetDlgItem(IDC_EDIT1)->SetWindowTextW(ss);
	}
	
}
unsigned char hex_to_bcd(unsigned char data)
{
	unsigned char temp;

	temp = (((data / 10) << 4) + (data % 10));
	return temp;
}

int CMainFrame::SummaryLog(int nThIdx)
{
	//return 0;
	int i = 0;
	time_t t = time(0);
	CWin32Heap stringHeap(HEAP_NO_SERIALIZE, 0, 0);
	CAtlStringMgr stringMgr(&stringHeap);
	CString strShow(&stringMgr);

	TCHAR tmp[64];
	TCHAR swzPath[MAX_PATH];
	TCHAR swzPathPrj_ChipSel[MAX_PATH];
	struct tm newtime;
	localtime_s(&newtime, &t);
	wcsftime(tmp, sizeof(tmp), L"%X", &newtime);

	//时间
	strShow.Format(L"%s  ", tmp);
	//日期
	wsprintf(tmp, L"%02d%02d%02d", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday);

	

	wcscpy_s(swzPath, g_wszCurPath);
	wcscat(swzPath, L"Log\\");
	wcscpy_s(swzPathPrj_ChipSel, swzPath);
	if (INCHIPSEL == m_nChipSel_Prj)
	{
		wcscat(swzPathPrj_ChipSel, L"ChipSel\\");
		wcscat(swzPathPrj_ChipSel, m_strChipSel_PrjName);

	}
	else if (INPRJ == m_nChipSel_Prj)
	{
		wcscat(swzPathPrj_ChipSel, L"Prj\\");
		if (wcslen(m_wszPrjPathSubDirInIni))
		{
			wcscat(swzPathPrj_ChipSel, m_wszPrjPathSubDirInIni);
			wcscat(swzPathPrj_ChipSel, L"\\");
		}
		wcscat(swzPathPrj_ChipSel, m_strChipSel_PrjName);
	}


	wcscat(swzPath, tmp);
	
	if (m_nChipSel_Prj)
	{
		wsprintf(swzPathPrj_ChipSel + wcslen(swzPathPrj_ChipSel), L"_%s", g_wszMachName);
	}
	//查找文件夹非法字符
	strShow = swzPathPrj_ChipSel;
	//strShow.Replace(L'\\',L'_');
	strShow.Replace(L'/',L'_');
	wcscpy(swzPathPrj_ChipSel, strShow.GetBuffer());
	wcscat(swzPathPrj_ChipSel, L"_sum.log");
	CFile fd;
	int ret = fd.Open(swzPathPrj_ChipSel, CFile::modeCreate | CFile::modeWrite);
	
	if (0 == ret)
	{
		strShow.Format(L"Open Prog%d LogSum Fail",nThIdx);
		pFormView3->RichEditShow(nThIdx, strShow, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
		return -1;
	}
	char szBuf[256];
	int nTotalCnt=0,nTotalFail=0;
	m_LogSumFile.Lock();
	for (i = 0; i < PROGRAMERMAXNUM; i++)
	{
		nTotalCnt += stu_UsbDeviceArr[i].nTotalCnt;
		nTotalFail += stu_UsbDeviceArr[i].nTotalFailCnt;

	}
	
	sprintf(szBuf, "Total=%d,Fail=%d", nTotalCnt, nTotalFail);
	fd.Write(szBuf, strlen(szBuf));
	fd.Close();
	m_LogSumFile.Unlock();
	return 0;
}


UCHAR gSendbuf[16 * 1024 * 1024];
UCHAR gReadbuf[4 * 1024 * 1024];
#define SIZE16MB   (16 * 1024 * 1024)
#define SIZE4MB   (4 * 1024 * 1024)
#define SIZE2MB   (2 * 1024 * 1024)
#define PROC_END 0
#define PROC_CANCEL 1
#define PROC_ERRSTOP 2
//适配器全报错
#define PROC_SOCKETALLERR  3


//四个MAP不同之处
//pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread0, (LPVOID)pThis);
//AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap0, (LPVOID)pThis);
//PRESSURElOOP
//PCEND
//PCCANCEL
//USBERR
DWORD WINAPIV CMainFrame::UsbDataProcFileMap0(LPVOID lParam)
{

	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR *pSendbuf = gSendbuf;
	UCHAR *pReadbuf = gReadbuf;
	CProgressCtrl *pCProgress = &pThis->pFormView2->m_progress0;


	CTimeSpan Timedif;
	int delay;
	CTime TimeBegin = CTime::GetCurrentTime();
	CTime TimeEnd;

	int len;
	int nThIdx = 0;
	int nBufDfLen;
	TCHAR wszPath[MAX_PATH];

	TCHAR wsztemp[180];

	BYTE inEpAddress = 0x83, outEpAddress = 0x01;
	UCHAR cStatus = PROC_END;
	int base = 0;
	UINT *pInt;
	bool ret = 0;
	CString strtmp, showstr = L"";
	PUCHAR		buffersInput = pReadbuf;
	CCyUSBEndPoint *epBulkOut = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(outEpAddress);
	CCyUSBEndPoint *epBulkIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(0X81);
	CCyUSBEndPoint *epBulkCmdIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(inEpAddress);
	long writelenth = 0;
	long nWarnLed = 0;
	long nScale = 0;
	UCHAR *pcData;
	UINT checksum = 0;
	UINT nCheckSums[BUFNUM] = {0,0,0,0,0,0,0,0,0,0};
	UINT nBufferIdxRd[BUFNUM] ={0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
	long readLenth = 1024 * 1024;
	short wColoridx;
	int wErrMaskinoneproc = 0;
	int nNoticeBlue = 0;
	int nNoticePurple = 0;
	UINT64 llSeekAddr = 0;
	UINT nSnOfset;
	//最高位是1表示是读的BUF.
	UCHAR cBufIdx = 0;
	UCHAR  crCurBufIdx = 0;
	//当前读BUFFER idx
	UCHAR  cwCurBufIdx = 0;
	UINT nSeekL = 0;
	USHORT wBufIdx8_Haddr8 = 0;
	if (epBulkOut == NULL || epBulkCmdIn == NULL || epBulkIn == NULL) return 1;
	int i, idx = 0;
	char cIs512Multy = 0;
	INT nSocketMax=SOCKETMAX;
	int nSocketSenseMask = 0;
	
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		nSocketMax = 2 * SOCKETMAX;
	CString path;
	
	
	
	CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[0]);
	path.Format(L"%slib\\%s", g_wszCurPath, wsztemp);
	path += L".bf";
	//创建文件对象
	CFileException e;
	CFile64 wfile;
	CFile64 rfile;
	int nSnChnIdx = 0;
	int nNeedDelKey = 0;
	CFile SnFile;
	int nBtnIdx;//= pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
//	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
//	strtmp += L" BEGIN...";


	for (i = 0; i < nSocketMax; i++)
	{
		//使能的SOCKET都RUN
		if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit & (1 << i))
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax * (pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_RUN;
		}
		else
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax * (pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_DISABLE;
		}

	}

	g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = SER_PROG_RUNNING;
	
	//Sleep(THDLY);
	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_RUN;
	//pThis->pFormView3->RichEditShow(nThIdx, L"", OPERATIONCOLOR, 0, 30);
	//如果是读.开读的文件
	if (pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'r')
	{
		if (pstuDevInfo[g_curDeviceSel].m_nReadConfirm)
		{
			if (MB_OK != pThis->MessageBox(L"请确保数据正确，否则芯片将被擦除", L"注意", MB_OKCANCEL))
			{
				pThis->m_pThreadUsbData[nThIdx] = NULL;
				return 0;
			}
		}
#if 0
		if (!wfile.Open(pThis->m_strReadFileDefaultPath[0], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
		{
			strtmp.Format(L"Failed to open the file %s\n", e.m_strFileName);
			AfxMessageBox(strtmp);
			epBulkCmdIn->Abort();
			epBulkOut->Abort();

			pThis->m_pThreadUsbData[nThIdx] = NULL;
			return 0;
		}
#endif
	}
	
	
	
	if (0 == pThis->nAutoSenseAutoRun)
	{
		//没选autosense
		//单步或者AUTO 第一步,才需要下载算法。FPGA等。AUTO的后面几步就不需要了//叠料//非空擦除第一次擦除
		if ((pThis->m_nIsAuto[nThIdx] == 0) || ((pThis->m_nIsAuto[nThIdx]) && (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0)) || pThis->stu_overlap.nIsOverLapCheck[nThIdx] ||
			(g_nEraseWhenNOTBlank && ('e' == pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]])))
		{
		
			ret=pThis->DownloadConfig_GetPincheck(nThIdx);
		}
	}
	
	else	
	{

		//选了AUTOsense，第一次要DownloadConfig_GetPincheck0，之后每个AUTO的第一次只要要SendConfiWord就行
		if ((pThis->stu_AutoSeq[nThIdx].nCurAutoIdx==0)|| (0 == pThis->nAutoLoopFirst[nThIdx]))
		{
			pThis->pFormView3->RichEditShow(nThIdx, L"Please insert new chips.....", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 20);
			while (1)
			{

				if (0 == pThis->nAutoLoopFirst[nThIdx])
				{
					ret = pThis->DownloadConfig_GetPincheck(nThIdx);
					if (ret)break;

				}
				else
				{
					ret = pThis->SendConfiWord(nThIdx, 3, pThis->m_cDownData[nThIdx], sizeof(pThis->m_cDownData[nThIdx]));
					if (ret)break;
				}
				pThis->PinSenseInAuto(nThIdx, pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
			
				pThis->pFormView2->SenseBlink(nThIdx);
				
				for (i = 0; i < SOCKETMAX; i++)
				{
					if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit & (1 << i))
					{
						//第一次接触上就行
						if (pThis->nAutoLoopFirst[nThIdx])
						{
							if (BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}
						else
						{
							//之后要有状态便话，有先取再放的过程
							if ((BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]) || (BLINK_NULL == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]))
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}

					}
				}
				pThis->nAutoLoopFirst[nThIdx] = 1;
				if (nSocketSenseMask == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)break;
				//停止
				if (0 == (pThis->nAutoSenseAutoRunStartEnd % 2))
				{

					memset(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx]));
					//	memset(stu_PinCheckBlink.nStartBlinkArr[i], 0, sizeof(stu_PinCheckBlink.nStartBlinkArr[i]));
					memset(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx]));
					pThis->m_nAutoCntPressure[nThIdx] = 0;
					pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
					pThis->m_pThreadUsbData[nThIdx] = NULL;
					pThis->nAutoSenseAutoRunStartEnd = 0;
					pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
					for (i = 0; i < SOCKETMAX; i++)
					{
						if (BLINK_START == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
						{
							pThis->pFormView2->mp_Static_ModArr[nThIdx][i]->SetIcon(pThis->pFormView2->stu_PinCheckBlink.HiconsavedIcon[nThIdx][i]);
						}
					}
					return 0;

				}
			}
		}
	}
	if (ret)
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		return 0;
	}
		 nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	strtmp += L" BEGIN...";
	pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 30);
	

		strtmp= path;
		showstr = pThis->m_strReadFileDefaultPath[0];
		//if (strtmp.MakeUpper() != showstr.MakeUpper())
		{
#ifdef SNPROGRAM
			if (!rfile.Open(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, OPEN_EXISTING, &e))
#else
			if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
#endif
			{
				strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				return 0;
			}
		}
		strtmp.Empty();
		showstr.Empty();
	
	

	//OVERLAPPED		OutOvLap;
	//UCHAR *outContext;
	//延续上次的错误状态码
	wErrMaskinoneproc |= pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus;
	//传输数据是否512字节的倍数，要处理，否则，传输死机
	

		//如果是RTCSETTING，此时BTN的显示必须是“RTCTimeInit”,就将当前时间保存到BUF0
		if (pThis->n_IsInRTCSetting)
		{
			if (rfile.IsClosed())
			{
				rfile.Open(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, OPEN_EXISTING, &e);
			}
		

					SYSTEMTIME st;
			UCHAR cData;
			GetLocalTime(&st);
			if (pThis->n_IsInRTCSetting == 1)
			{
				cData = hex_to_bcd(st.wYear - 2000);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wMonth);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wDay);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wHour);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wMinute);
				rfile.Write(&cData, 1);
			}
			//snwrite
			else if (pThis->n_IsInRTCSetting == 2)
			{
				cData = hex_to_bcd(st.wYear - 2000);
				rfile.Seek(0x30, CFile64::begin, 1);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wMonth);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wDay);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wHour);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wMinute);
				rfile.Write(&cData, 1);
			}
			//sktwrite
			else if (pThis->n_IsInRTCSetting == 3)
			{
				cData = hex_to_bcd(st.wYear - 2000);
				rfile.Seek(0x10, CFile64::begin, 1);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wMonth);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wDay);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wHour);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wMinute);
				rfile.Write(&cData, 1);
			}
			else if (pThis->n_IsInRTCSetting == 4)
			{
				cData = hex_to_bcd(st.wYear - 2000);
				rfile.Seek(0x50, CFile64::begin, 1);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wMonth);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wDay);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wHour);
				rfile.Write(&cData, 1);
				cData = hex_to_bcd(st.wMinute);
				rfile.Write(&cData, 1);
			}
			rfile.Close();
			rfile.Open(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, OPEN_EXISTING, &e);
		//	rfile.Close();


		}
		
			
	
	



	//要注意的是,必须先操作完 pBuffer才能UnmapViewOfFile,
	//如果先UnmapViewOfFile,再操作 pBuffer则会出错,因为pBuffer已经被释放了
	pInt = (UINT*)pSendbuf;
	pcData = (UCHAR *)pSendbuf;

	epBulkOut->Abort();
	epBulkOut->Reset();
	epBulkCmdIn->Abort();
	epBulkCmdIn->Reset();
	epBulkIn->Abort();
	epBulkIn->Reset();

	//strtmp.Format(L"checksum=%u\n", checksum);
	pCProgress->SetRange(0, 100);
	epBulkOut->TimeOut = INFINITE;
	epBulkCmdIn->TimeOut = INFINITE;
	checksum = 0;
	int nSktCnt=0;

	//面板LED显示

	if (pThis->m_pThreadUserProc1[nThIdx] != NULL)
	{
		strtmp.Format(L"site%d thread proc ptr NOT NULL", pThis->m_nSiteNo[nThIdx]);
		AfxMessageBox(strtmp);
	}


	OVERLAPPED ovLapStatus;
	memset(&ovLapStatus, 0, sizeof(OVERLAPPED));
	ovLapStatus.hEvent = CreateEvent(NULL, false, false, NULL);
	


	int nMutex = 0;
	while (1)
	{
				
		PUCHAR context = epBulkCmdIn->BeginDataXfer(buffersInput, readLenth, &ovLapStatus);
		if (nMutex == 0)
		{
			nMutex = 1;
			pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread, (LPVOID)&nThIdx);
		}
		
		bool   wResult = epBulkCmdIn->WaitForXfer(&ovLapStatus,INFINITE);
		bool   fResult = epBulkCmdIn->FinishDataXfer(buffersInput, readLenth, &ovLapStatus, context);

	    
		 ret =wResult && fResult;
		 if (ret != true)
		 {
			 CloseHandle(ovLapStatus.hEvent);
			 epBulkCmdIn->Abort();
			 epBulkOut->Abort();
			 //取消映射
			 if (rfile.IsOpen()) rfile.Close();
			 if (wfile.IsOpen()) wfile.Close();
			 pThis->pFormView3->RichEditShow(nThIdx, L"USB data req transfer err", COLOR_RED, 0, 0);
			 //关闭文件映射对象
			 pThis->m_pThreadUsbData[nThIdx] = NULL;
			 return -1;
		 }

		//OUT数据，主要流程，烧录,校验
		if (buffersInput[0] == 'O')
		{
			cIs512Multy = buffersInput[1] & 4;
			memcpy(&writelenth, &buffersInput[2], 4);
			//0,1:SINGLE 和双BUFFER的STARTSTORE
			if ((buffersInput[1] & 3) <= 1)
			{
				if (cIs512Multy)
				{
					len=rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}

				}
				else
				{
					len=rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth -  len);
					}
				}

				//KEY SN
				if ((cBufIdx & 0x7f) == BUFNUM)
				{
					pThis->m_CriticalSectionKey.Lock();
					//pThis->pFormView3->RichEditShow(0, L"in 0 begin", COLOR_RED, 0, 0);
					//[0:3]第几组序列,低4位，,其余是OFFSET
					//[4]删除KEY文件吗
					//[5:31]OFFSET
					nSnChnIdx = llSeekAddr&0xf;
					nNeedDelKey = ((llSeekAddr >> 4) & 1);
					nSnOfset = llSeekAddr >>5;
					//取得几个序列号
					if (pThis->stu_GenSetting.nUserSnLen[nSnChnIdx])
					{
						int nSnCnt = writelenth / pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						writelenth = nSnCnt*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						if (writelenth > SIZE16MB-1)
						{
							writelenth = SIZE2MB-1;
							pThis->pFormView3->RichEditShow(nThIdx, L"change to 2MB(Key must <2MB)", COLOR_RED, 0, 0);
						}
						pThis->GetOneUserSn(nThIdx, nSnChnIdx, nSnOfset, nNeedDelKey, nSnCnt);
						pcData[0] = pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum;
					
						memcpy(pcData+1, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr, writelenth);
						writelenth += 1;
					}
					else
					{
						writelenth = 2;
						memset(pcData, 0, writelenth);
					}
				//	pThis->pFormView3->RichEditShow(0, L"in 0 end", COLOR_RED, 0, 0);
					pThis->m_CriticalSectionKey.Unlock();
				}
				//等待三秒

				epBulkOut->XferData(pcData, writelenth);

				

			}

#if 1

			//下一次准备
			//memset(pcData, 1, 1024);
			//双buffer

			if ((buffersInput[1] & 2))
			{
				if (cIs512Multy)
				{
					len=rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len=rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}



				epBulkOut->XferData(pcData, writelenth);


			}
			//
#endif

		}
		//IN数据，读
		else if (buffersInput[0] == 'I')
		{
			//防止第二次读其他BUFFER导致重新打开BUFFER0，把BUFFER0之前读得数据干掉。设为读得时候如果没有BUFFERSEEK没有打开文件。那么这里才开BUFFER
			if (wfile.IsClosed())
			{
				//EMMC第一次读，查看是否同名文件.bf是打开的。
				if (rfile.IsOpen())
				{
					if (rfile.GetFileName() == pThis->m_strReadFileDefaultPath[cwCurBufIdx])
					{
						rfile.Close();
					}
				}
				if (!wfile.Open(pThis->m_strReadFileDefaultPath[cwCurBufIdx], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
				{
					strtmp.Format(L"Failed to open the file %s\n", e.m_strFileName);
					AfxMessageBox(strtmp);
					epBulkCmdIn->Abort();
					epBulkOut->Abort();

					pThis->m_pThreadUsbData[nThIdx] = NULL;
					return 0;
				}
			}
			if (g_nIsEmmc)
			{
				pThis->m_nIsLoadBufferDll = 1;pThis->m_nIsReadFitnessNeedDataAnalysis=1;
			}
			cBufIdx |= 0x80;
			len = wfile.GetPosition();
			//把读之前SEEK的位置加上去
			if (llSeekAddr > len)
			{
				//如果要填充1
				if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cwCurBufIdx & 0x7f], "0"))
				{
					memset(pSendbuf, 0xff, SIZE16MB);
					len = llSeekAddr - len;
					for (i = 0; i < len / SIZE16MB; i++)
					{
						wfile.Write(pSendbuf, SIZE16MB);
						nCheckSums[cwCurBufIdx]=checksum += CalcCheckSum(pSendbuf, SIZE16MB);
					}

					if (len%SIZE16MB)
					{
						wfile.Write(pSendbuf, len%SIZE16MB);
						nCheckSums[cwCurBufIdx]=checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
					}
				}
				else
				{
					//直接填0
					wfile.Seek(llSeekAddr, CFile64::begin, 1);
				}


			}

			memcpy(&readLenth, &buffersInput[2], 4);
			ret = epBulkIn->XferData(buffersInput, readLenth);
			if (ret != true)
			{
				CloseHandle(ovLapStatus.hEvent);
				epBulkCmdIn->Abort();
				epBulkOut->Abort();
				epBulkIn->Abort();
				//取消映射
				if (rfile.IsOpen()) rfile.Close();
				if (wfile.IsOpen()) wfile.Close();
				pThis->pFormView3->RichEditShow(nThIdx, L"USB data in transfer err", COLOR_RED, 0, 0);
				//关闭文件映射对象
				pThis->m_pThreadUsbData[nThIdx] = NULL;
				return -1;
			}
			wfile.Write(buffersInput, readLenth);
			nCheckSums[cwCurBufIdx]=checksum += CalcCheckSum(buffersInput, readLenth);
			nBufferIdxRd[cwCurBufIdx] = 1;
			len = wfile.GetPosition();
		}
		//正常结束和CANCEL
		else if (buffersInput[0] == 'C')
		{
			if (0 == buffersInput[2])
			{
				//正常退出

				if (0 == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
				{
					//socket号都不对
					pThis->m_nIsAuto[nThIdx] = 0;
					cStatus = PROC_SOCKETALLERR;
				}
				//读追加文件末尾填充
				if (cBufIdx & 0x80)
				{
					if (wfile.IsOpen())
					{
						len = wfile.GetPosition();
						sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f], "%x", &nBufDfLen);
						//要追加填充
						if (nBufDfLen > len)
						{
							//如果要填充1
							if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cBufIdx & 0x7f], "0"))
							{
								len = nBufDfLen - len;
								memset(pSendbuf, 0xff, SIZE16MB);
								for (i = 0; i < len / SIZE16MB; i++)
								{
									wfile.Write(pSendbuf, SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
								}

								if (len%SIZE16MB)
								{
									wfile.Write(pSendbuf, len%SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
								}
							}
							else
							{
								//直接填0
								wfile.Seek(nBufDfLen, CFile64::begin, 1);
							}

						}
					}
					
				}

				//if (cBufIdx & 0x80)
				{
					for (i = 0; i < BUFNUM; i++)
					{
						if (nBufferIdxRd[i])
						{
							CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);
							
							strtmp.Format(L"%s Checksum=0x%08x", wsztemp, nCheckSums[i]);
							
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
							if (g_nIsEmmc)pThis->pFormView2->DispChecksumInListCtrl(pThis->m_cComboBufSelMap[i], nCheckSums[i], nCheckSums[i]);
						}
					}
					
				}

				

				goto PCEND;
			}
			//
			else if (1 == buffersInput[2])
			{
				//cancel
				//	strtmp.Format(L"Cancel thread %s\n", __FUNCTIONW__);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 0, pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit);
				pCProgress->SetPos(0);
				//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

				cStatus = PROC_CANCEL;
				pThis->m_nIsAuto[nThIdx] = 0;
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				//pThis->Beep(nThIdx, 0);
				goto PCCANCEL;

			}
			//算法FAIL上报
			else if (2 == buffersInput[2])
			{
				//cancel
				strtmp.Format(L"Fail\n");
				pCProgress->SetPos(0);
				if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				cStatus = PROC_END;
			
				
				goto PCEND;

			}

		}
		//DEBUGSTRING
		else if (buffersInput[0] == 'D')
		{
			if (0xff == ((UCHAR)buffersInput[2]))
			{
				int nColor = (buffersInput[3] << 16) | (buffersInput[4] << 8) | (buffersInput[5] );
				CharToTchar(wsztemp, (const char*)(buffersInput + 2+4));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, nColor, 0, 0);
			}
			else
			{
				CharToTchar(wsztemp, (const char*)(buffersInput + 2));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
			}
			

		}
		//进度条 PROGRESS
		else if (buffersInput[0] == 'P')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			pCProgress->SetPos(nScale);
			g_SerialResBuf[SERSOCKBASE + nSocketMax* 32 + (pThis->m_nSiteNo[nThIdx] - 1)] = nScale;

		}
		else if (buffersInput[0] == 'X')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			memcpy(g_ConfigData.nData, &buffersInput[2], 498);

			
		}
		//BufferSeek
		else if (buffersInput[0] == 'S')
		{
			checksum = 0;
			memcpy(&nSeekL, &buffersInput[2], 4);
			memcpy(&wBufIdx8_Haddr8, &buffersInput[2 + 4], 2);
			llSeekAddr = (UINT64)(wBufIdx8_Haddr8 &0XFF)<< 32| nSeekL;
		
			cBufIdx = wBufIdx8_Haddr8 >> 8;
			//获得SN
			if ((cBufIdx & 0x7f) == BUFNUM)
			{
					
			}
			//写操作的BUFFER NUM与大于MAX
			else if (((cBufIdx & 0x7f) > BUFNUM) && ((cBufIdx & 0x80) == 0))
			{
				strtmp.Format(L"Buffer Idx>%d error\n", BUFNUM);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				pThis->Beep(nThIdx, 2);
				goto PCCANCEL;
			}

			//写操作时DEVICE没有这个BUFFER NUMBER
			else if (((cBufIdx & 0x80) == 0) && ((0 == strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[cBufIdx & 0x7f])) || (0 == strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f]))))
			{
				strtmp.Format(L"Buffer Idx %d Invalid\n", cBufIdx);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				goto PCCANCEL;
			}
			else if ((0 == (cBufIdx & 0x80)) && ((cBufIdx & 0X7F) == crCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是写操作

				rfile.Seek(llSeekAddr, CFile64::begin, 1);

			}
			else if ((cBufIdx & 0x80) && ((cBufIdx & 0X7F) == cwCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是读，啥也不干
			}
			//不同要重新打开文件
			else
			{
				//	if (Curfile.IsOpen())
				{

					//读操作
					if (cBufIdx & 0x80)
					{
						//无论是否打开，当前读BUFFER idx都要更新
						cwCurBufIdx = cBufIdx & 0X7F;
						if (wfile.IsOpen())
						{
							wfile.Close();
							strtmp.Format(L"wBuf%d closed", cwCurBufIdx);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
							
							//读直接用路径，不是BUFX
							
							path = pThis->m_strReadFileDefaultPath[cBufIdx & 0x7f];
							if (rfile.IsOpen())
							{
								if (rfile.GetFileName() == pThis->m_strReadFileDefaultPath[cwCurBufIdx])
								{
									rfile.Close();
								}
							}
						
							if (!wfile.Open(path, GENERIC_WRITE, 0, OPEN_ALWAYS, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								return 0;
							}

							//strtmp.Format(L"buf%d open,seek %d\n", cwCurBufIdx, llSeekAddr);
						}

					}
					//写操作
					else
					{
						if (rfile.IsOpen())
						{
							rfile.Close();
							//strtmp.Format(L"wBuf%d closed", crCurBufIdx);
						//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
						}
							crCurBufIdx = cBufIdx & 0X7F;
							CharToTchar(wszPath, pstuDevInfo[g_curDeviceSel].szBufNameArrs[crCurBufIdx]);
							path.Format(L"%slib\\%s", g_wszCurPath, wszPath);
							//path.Format(L"%slib\\%s", g_wszCurPath, pstuDevInfo[g_curDeviceSel].szBufNameArrs[crCurBufIdx]);

							path += L".bf";
							if (wfile.IsOpen())
							{
								if (wfile.GetFileName() == path)
								{
									wfile.Close();
								}
							}
						
							if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								return 0;
							}
							rfile.Seek(llSeekAddr, CFile64::begin, 1);
						//	strtmp.Format(L"buf%d open,seek %d\n", crCurBufIdx, llSeekAddr);
						
					}


					//读的话，需要在读到数据的时候填充，不要直接SEEK，

					//if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);

				}
			}

		}
		//LED状态显示颜色
		else if (buffersInput[0] == 'W')
		{
			memcpy(&nWarnLed, &buffersInput[2], 4);
			//pCProgress->SetPos(nScale);
			wColoridx = nWarnLed >> 16;
			//低16位是掩码

				if (WARNCOLOR_RED == wColoridx)
				{
					//有错误才显示红灯
					for (i = 0; i < nSocketMax; i++)
					{
						if (nWarnLed&(1 << i))
						{
							//重复SOCKET只显示一次
							if (0 == (wErrMaskinoneproc&(1 << i)))
							{
								if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
								{

									strtmp.Format(L"socket%d Failure", i + 1);
									if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 2);
								}

							}

						}
					}
					wErrMaskinoneproc |= (nWarnLed & 0xffff);

					pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				}
				else if (WARNCOLOR_BLUE == wColoridx)
				{
					nNoticeBlue |= (nWarnLed & 0xffff);

					pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticeBlue&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				}
				else if (WARNCOLOR_PURPLE == wColoridx)
				{
					nNoticePurple |= (nWarnLed & 0xffff);

					pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticePurple&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				}
				
			else
			{
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nWarnLed&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}

		}

		if (ret != true)
		{
			pThis->stu_UsbDeviceArr[nThIdx].status = USBNOTCONNECT;

			//SOCKET设置未连接
			g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = USBNOTCONNECT;
			memset(&g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax], SER_SOCKET_DISABLE, nSocketMax);
			memset(&pThis->stu_AutoSeq[nThIdx], 0, sizeof(pThis->stu_AutoSeq[nThIdx]));
			cStatus = PROC_ERRSTOP;
			goto USBERR;

		}

	}

PCEND:
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	//如果选了叠料
	if (pThis->stu_overlap.nIsOverLapCheck[nThIdx])
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Checking", COLOR_YELLOW, 0, 0);
		wErrMaskinoneproc = (~(wErrMaskinoneproc))&(pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
		pThis->stu_overlap.nOverLapSockFail[nThIdx] = wErrMaskinoneproc;

		pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, pThis->stu_overlap.nOverLapSockFail[nThIdx]);
		//如果校验成功，代表叠料了

		if(pThis->stu_overlap.nOverLapSockFail[nThIdx])
		{
			if (pThis->stu_overlap.nOverLapSockFail[nThIdx] == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Check Fail", COLOR_RED, 0, 0);
				
			}
			
			for (i = 0; i < SOCKETMAX; i++)
			{
				if((1<<i)&(pThis->stu_overlap.nOverLapSockFail[nThIdx] ))
				{
					strtmp.Format(L"Sok %d overlap Fail", i + 1);
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				}
			}
			
		}
		
	}
		
	//如果选了空检查出错擦除，第一步是空检查，都OK的情况下，直接跳过下面的ERASE
	else if((pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'b')&&(g_nEraseWhenNOTBlank))
	{
		if(wErrMaskinoneproc==0)
		{
			pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;						
		}
		//g_nEraseWhenNOTBlank==1在BLANK中ERRMASK不能设置1，否则会导致后面退出
		wErrMaskinoneproc = 0;

	}
	
	//全错，又不是blank且g_nEraseWhenNOTBlank=0，则停止
	if (wErrMaskinoneproc == pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)
	{
		pThis->m_nIsAuto[nThIdx] = 0;
	}
PCCANCEL:
	pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus |= (wErrMaskinoneproc|pThis->stu_overlap.nOverLapSockFail[nThIdx]);


	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
USBERR:
	CloseHandle(ovLapStatus.hEvent);
	epBulkCmdIn->Abort();
	epBulkOut->Abort();
	//CloseHandle(OutOvLap.hEvent);
	//取消映射
	if (rfile.IsOpen())
		rfile.Close();
	if (wfile.IsOpen())
	{
		wfile.Close();
	}
	

	//关闭文件映射对象

	pThis->m_pThreadUsbData[nThIdx] = NULL;
	
	if (cStatus == PROC_CANCEL)
	{
		strtmp.Empty();
	}
	//如果SOCKET全部报错。就不报下面这些FINISHED了
	if (cStatus != PROC_SOCKETALLERR)
	{
		if (cStatus == PROC_CANCEL)
			strtmp += L" Canceled";
		else
		{
			if (0 == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" SUCCESS";
			}
			else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" FAIL";
			}
			else
			strtmp += L" FINISHED";
		}
		if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 30);
		TimeEnd = CTime::GetCurrentTime();
		Timedif = TimeEnd - TimeBegin;
		delay = Timedif.GetMinutes() * 60 + Timedif.GetSeconds();
		strtmp.Format(L"%d seconds", delay);
		pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
		//pThis->pFormView3->RichEditShow(nThIdx, L"", OPERATIONCOLOR, 0, 0);


	}
	


	if ((cStatus == PROC_END) || (cStatus == PROC_CANCEL))
	{
		//AUTO中
		if (pThis->m_nIsAuto[nThIdx])
		{
			//叠料检测那次不++；
			if (pThis->stu_overlap.nIsOverLapCheck[nThIdx] == 0)
			{
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;
				
			}
			else pThis->stu_overlap.nIsOverLapCheck[nThIdx] = 0;


		PRESSURElOOP:


			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx < pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				//中途掉线就不AUTO哦了
				if (pThis->stu_UsbDeviceArr[nThIdx].status != USBNOTCONNECT)
					AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap0, (LPVOID)pThis);
			}
			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				
			}
		}
		//单次或者AUTO最后一次
		if (pThis->m_nIsAuto[nThIdx] == 0)
		{
			pThis->m_FailSktLastAuto[nThIdx] = wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit;
			if (pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{	
				pThis->m_nIsAuto[nThIdx] = 0;
				if (0xff == (pThis->m_nBtnIdx & 0xff))
				{//确保是AUTO
					if (0 == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO SUCCESS";
					}
					else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO FAIL";
					}
					else
						strtmp = L"AUTO FINISHED";
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
				}
			
			}


#ifdef SNPROGRAM
			if (pThis->n_IsInRTCSetting == 3)
			{
				pThis->pFormView2->m_UniqSN.GetWindowText(wsztemp, 50);
				
				swscanf(wsztemp, L"%u", &nSktCnt);
			}
#endif
			//统计
			for (i = 0; i < nSocketMax; i++)
			{
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{

					if ((wErrMaskinoneproc|pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus)&(1 << i))
					{

						pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[i]++;
						pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt++;
					}
#ifdef SNPROGRAM
					else
					{
						//写SOCKET时候UNIT 
					
							nSktCnt++;					
					}
#endif
					pThis->stu_UsbDeviceArr[nThIdx].nSokTotalCnt[i]++;
					pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt++;
				}
#ifdef SNPROGRAM
			if (pThis->n_IsInRTCSetting == 3)
			{
				wsprintf(wsztemp, L"%u", nSktCnt);
				pThis->pFormView2->m_UniqSN.SetWindowText(wsztemp);
				//写入INI
				TCHAR swzinipath[MAX_PATH];
				wcscpy_s(swzinipath, g_wszCurPath);
				wcscat_s(swzinipath, L"setting.ini");
				
				TCHAR swzSector[50];
				char szSector[50];
				pThis->pFormView2->m_EditSockeSN.GetWindowTextW(swzSector, 50);
				TcharToChar(szSector, swzSector);
				szSector[11] = 0;
				CharToTchar(swzSector, szSector);
				
				WritePrivateProfileString(L"AdapterIndx", swzSector, wsztemp, swzinipath);
			}
		
#endif
			}
			strtmp.Format(L"Total:%d  Success:%d  Fail:%d", pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt - pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 40);
			strtmp.Format(L"SockFail %d,%d,%d,%d,%d,%d,%d,%d", pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[0], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[1], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[2], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[3], \
				pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[4], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[5], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[6], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[7]);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 0);
			pThis->SummaryLog(nThIdx);
			//根据nSockProgStatus ,失败的写回SN 文件
			//if (nNeedDelKey)
			{
				for (nSnChnIdx = 0; nSnChnIdx<pThis->stu_GenSetting.nCnt; nSnChnIdx++)
				{
					if (pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum > 0)
					{
						idx = 0;
						pThis->m_CriticalSectionLog.Lock();
						for (i = 0; i < SOCKETMAX; i++)
						{
							//SOCKET不为空
							if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit&(1 << i))
							{
								//失败，SN码一一写回
								//失败，从KEYPSD文件夹MOVEBACK
								//char path_buffer[_MAX_PATH];
								TCHAR drive[_MAX_DRIVE];
								TCHAR dir[_MAX_DIR];
								TCHAR fname[_MAX_FNAME];
								TCHAR ext[_MAX_EXT];
								_wsplitpath(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], drive, dir, fname, ext);
								if (pThis->stu_GenSetting.nIsDelete)
								{
									strtmp = g_wszCurPath;
								}
								else
								{
									strtmp = drive;
									strtmp += dir;
								}

								strtmp += L"KPsd\\";
								strtmp += fname;
								strtmp += ext;
								//返回结果有错误，同时又是使能的SOCKET
								if (0 != (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i)))
								{

								}
								else
								{

									DeleteFile(strtmp);
									if (0 == MoveFile(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], strtmp))
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										strtmp += L" move fail";
										pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

									}
									else
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										if (wcslen(fname))
										{

											strtmp += L" moved";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
										//	pThis->m_CriticalSectionLog.Lock();
											if (pThis->stu_GenSetting.nIsDelete)
											{
												strtmp = g_wszCurPath;
											}
											else
											{
												strtmp = drive;
												strtmp += dir;
											}

											strtmp += L"KPsd\\";
										
										//	pThis->pFormView3->RichEditShow(0, L"0 log begin", COLOR_PINK_CLEAR, 0, 0);
										//	pThis->pFormView3->RichEditShow(0, fname, COLOR_YELLOW, 0, 0);
										pThis->logPsdKey0(strtmp, fname);
										//	pThis->pFormView3->RichEditShow(0, L"0 log end", COLOR_PINK_CLEAR, 0, 0);
											
										}
									}
									

								}
								idx++;

							}
						}
						pThis->m_CriticalSectionLog.Unlock();


					}
				}
			}
			
			
			if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				//全错 FAIL


				pThis->Beep(nThIdx, 2);


			}
			//成功，无错
			else if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->Beep(nThIdx, 0);
			}
			//计算时间
			if (cStatus != PROC_SOCKETALLERR)
			{
				pThis->m_TimeEnd[nThIdx] = CTime::GetCurrentTime();
				Timedif = pThis->m_TimeEnd[nThIdx] - pThis->m_TimeBegin[nThIdx];
				delay = Timedif.GetTotalSeconds();
				strtmp.Format(L"Total %d seconds", delay);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 3);
				pThis->pFormView3->RichEditShow(nThIdx, L"", OPERATIONCOLOR, 0, 0);
			}

			//删除KEY的记录
			for (i = 0; i < 10; i++)
			{
				pThis->stu_UserSNProg[nThIdx][i].nSnNum = 0;
				memset(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile, 0, sizeof(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile));
			}
			
			pThis->HighZ_CloseV(nThIdx);
		}

	}
	if (pThis->m_nIsAuto[nThIdx] == 0)
	{
		//串口 和网络
		if ((stu_RemoteStat.nRemoteStat > 0) && ((TRUE == stu_RemoteStat.isComOpened) || (pThis->m_SocketObject.IsOpen())))
		{
			for (i = 0; i < nSocketMax; i++)
			{
				//使能的SOCKET都RUN
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{
					//失败的
					if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i))
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
					//成功的
					else
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_OK;
					}

				}

				//未使能的，如果是SOCKET ERR=1，是座子号不对
				else
				{
				//	if (pThis->stu_UsbDeviceArr[nThIdx].cSokEncRet[i])
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
				}

			}
			g_SerialResBuf[(pThis->m_nSiteNo[nThIdx] - 1)] = SER_PROG_READY;


		}
		pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus = 0;
	}



	pThis->pFormView1->CntDisplayEachLeftListCtrl(nThIdx, 0);
	pThis->pFormView2->CntDisplayEachPanel(nThIdx);


	//压力测试
	//如果选择PINCHECK AUTO，使用压力测试的流程，把次数固定
	if (pThis->nAutoSenseAutoRun)
	{
		if (pThis->nAutoSenseAutoRunStartEnd % 2)
		{
			pThis->m_nAutoCntPressure[nThIdx] = 5;
		}
		else
		{
			pThis->m_nAutoCntPressure[nThIdx] = 0;
			pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
			pThis->nAutoSenseAutoRunStartEnd = 0;
			pThis->m_pThreadUsbData[nThIdx] = NULL;
			
		}
		
	}
	
	if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
	{
		if (pThis->m_nAutoCntPressure[nThIdx] > 0)
		{
			nSocketMax = 0;
			pThis->m_nAutoCntPressure[nThIdx]--;
			if (pThis->m_nAutoCntPressure[nThIdx] > 0)
			{
				pThis->m_nIsAuto[nThIdx] = 0xff;
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx = 0;
				
				goto PRESSURElOOP;
			}
		}
	}
	return 0;
}


UCHAR gSendbuf1[16 * 1024 * 1024];
UCHAR gReadbuf1[4 * 1024 * 1024];

//四个MAP不同之处
//pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread0, (LPVOID)pThis);
//AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap0, (LPVOID)pThis);
//PRESSURElOOP
//PCEND
//PCCANCEL
//USBERR
DWORD WINAPIV CMainFrame::UsbDataProcFileMap1(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR *pSendbuf = gSendbuf1;
	UCHAR *pReadbuf = gReadbuf1;
	CProgressCtrl *pCProgress = &pThis->pFormView2->m_progress1;

	CTimeSpan Timedif;
	int delay;
	CTime TimeBegin = CTime::GetCurrentTime();
	CTime TimeEnd;
	int len;
	int nThIdx = 1;
	int nBufDfLen;
	TCHAR wszPath[MAX_PATH];
	UINT nSnOfset;
	int nNeedDelKey = 0;
	TCHAR wsztemp[180];

	BYTE inEpAddress = 0x83, outEpAddress = 0x01;
	UCHAR cStatus = PROC_END;
	int base = 0;
	UINT *pInt;
	bool ret = 0;
	CString strtmp, showstr = L"";
	PUCHAR		buffersInput = pReadbuf;
	CCyUSBEndPoint *epBulkOut = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(outEpAddress);
	CCyUSBEndPoint *epBulkIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(0X81);
	CCyUSBEndPoint *epBulkCmdIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(inEpAddress);
	long writelenth = 0;
	long nWarnLed = 0;
	long nScale = 0;
	UCHAR *pcData;
	UINT checksum = 0;
	long readLenth = 1024 * 1024;
	UINT nCheckSums[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	UINT nBufferIdxRd[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	short wColoridx;
	int wErrMaskinoneproc = 0;
	int nNoticeBlue = 0;
	int nNoticePurple = 0;
	UINT64 llSeekAddr = 0;
	//最高位是1表示是读的BUF.
	UCHAR cBufIdx = 0;
	UCHAR  crCurBufIdx = 0;
	UCHAR  cwCurBufIdx = 0;
	UINT nSeekL = 0;
	USHORT wBufIdx8_Haddr8 = 0;
	if (epBulkOut == NULL || epBulkCmdIn == NULL || epBulkIn == NULL) return 1;
	int i, idx = 0;
	int nSocketSenseMask = 0;

	INT nSocketMax = SOCKETMAX;
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		nSocketMax = 2 * SOCKETMAX;

	for (i = 0; i < nSocketMax; i++)
	{
		//使能的SOCKET都RUN
		if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_RUN;
		}
		else
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_DISABLE;
		}

	}

	g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = SER_PROG_RUNNING;

	int nBtnIdx;
	//Sleep(THDLY);

	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_RUN;


	if (0 == pThis->nAutoSenseAutoRun)
	{
		//没选autosense
	//单步或者AUTO 第一步,才需要下载算法。FPGA等。AUTO的后面几步就不需要了//叠料//非空擦除第一次擦除
		if ((pThis->m_nIsAuto[nThIdx] == 0) || ((pThis->m_nIsAuto[nThIdx]) && (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0)) || pThis->stu_overlap.nIsOverLapCheck[nThIdx] ||
			(g_nEraseWhenNOTBlank && ('e' == pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]])))
		{
			ret = pThis->DownloadConfig_GetPincheck(nThIdx);
		}
	}

	else
	{
		//选了AUTOsense，第一次要DownloadConfig_GetPincheck0，之后每个AUTO的第一次只要要SendConfiWord就行
		if ((pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0) || (0 == pThis->nAutoLoopFirst[nThIdx]))
		{
			pThis->pFormView3->RichEditShow(nThIdx, L"Please insert new chips.....", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 20);
			while (1)
			{

				if (0 == pThis->nAutoLoopFirst[nThIdx])
				{
					ret = pThis->DownloadConfig_GetPincheck(nThIdx);
					if (ret)break;

				}
				else
				{
					ret = pThis->SendConfiWord(nThIdx, 3, pThis->m_cDownData[nThIdx], sizeof(pThis->m_cDownData[nThIdx]));
					if (ret)break;
				}
				pThis->PinSenseInAuto(nThIdx, pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
				pThis->pFormView2->SenseBlink(nThIdx);
				for (i = 0; i < SOCKETMAX; i++)
				{
					if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit & (1 << i))
					{
						//第一次接触上就行
						if (pThis->nAutoLoopFirst[nThIdx])
						{
							if (BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}
						else
						{
							//之后要有状态便话，有先取再放的过程
							if ((BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]) || (BLINK_NULL == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]))
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}

					}
				}
				pThis->nAutoLoopFirst[nThIdx] = 1;
				if (nSocketSenseMask == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)break;
				//停止
				if (0 == (pThis->nAutoSenseAutoRunStartEnd % 2))
				{

					memset(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx]));
					//	memset(stu_PinCheckBlink.nStartBlinkArr[i], 0, sizeof(stu_PinCheckBlink.nStartBlinkArr[i]));
					memset(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx]));
					pThis->m_nAutoCntPressure[nThIdx] = 0;
					pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
					pThis->m_pThreadUsbData[nThIdx] = NULL;
					pThis->nAutoSenseAutoRunStartEnd = 0;
					pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
					for (i = 0; i < SOCKETMAX; i++)
					{
						if (BLINK_START == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
						{
							pThis->pFormView2->mp_Static_ModArr[nThIdx][i]->SetIcon(pThis->pFormView2->stu_PinCheckBlink.HiconsavedIcon[nThIdx][i]);
						}
					}
					return 0;

				}
			}
		}
	}
	if (ret)
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		return 0;
	}
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	strtmp += L" BEGIN...";
	pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 30);

	//OVERLAPPED		OutOvLap;
	//UCHAR *outContext;
	//延续上次的错误状态码
	wErrMaskinoneproc |= pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus;
	//传输数据是否512字节的倍数，要处理，否则，传输死机
	char cIs512Multy = 0;



	CString path;
	CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[0]);
	path.Format(L"%slib\\%s", g_wszCurPath, wsztemp);
	path += L".bf";
	//创建文件对象
	CFileException e;
	CFile64 wfile;
	CFile64 rfile;
	int nSnChnIdx = 0;
	CFile SnFile;



	//如果是读.开读的文件
	if (pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'r')
	{
		/*if (!wfile.Open(pThis->m_strReadFileDefaultPath[0], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
			
			return 0;
		}*/
	}
	strtmp = path;
	showstr = pThis->m_strReadFileDefaultPath[0];
	//if (strtmp.MakeUpper() != showstr.MakeUpper())
	{
		if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
			return 0;
		}
	}
	strtmp.Empty();
	showstr.Empty();
	



	//要注意的是,必须先操作完 pBuffer才能UnmapViewOfFile,
	//如果先UnmapViewOfFile,再操作 pBuffer则会出错,因为pBuffer已经被释放了
	pInt = (UINT*)pSendbuf;
	pcData = (UCHAR *)pSendbuf;

	epBulkOut->Abort();
	epBulkOut->Reset();
	epBulkCmdIn->Abort();
	epBulkCmdIn->Reset();
	epBulkIn->Abort();
	epBulkIn->Reset();

	//strtmp.Format(L"checksum=%u\n", checksum);
	pCProgress->SetRange(0, 100);
	epBulkOut->TimeOut = INFINITE;
	epBulkCmdIn->TimeOut = INFINITE;
	checksum = 0;


	//面板LED显示

	if (pThis->m_pThreadUserProc1[nThIdx] != NULL)
	{
		strtmp.Format(L"site%d thread proc ptr NOT NULL", pThis->m_nSiteNo[nThIdx]);
		AfxMessageBox(strtmp);
	}
	OVERLAPPED ovLapStatus;
	memset(&ovLapStatus, 0, sizeof(OVERLAPPED));
	ovLapStatus.hEvent = CreateEvent(NULL, false, false, NULL);




	int nMutex = 0;
	while (1)
	{
	

		PUCHAR context = epBulkCmdIn->BeginDataXfer(buffersInput, readLenth, &ovLapStatus);
		if (nMutex == 0)
		{
			nMutex = 1;
			pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread, (LPVOID)&nThIdx);
		}
		
		bool   wResult = epBulkCmdIn->WaitForXfer(&ovLapStatus,INFINITE);
		bool   fResult = epBulkCmdIn->FinishDataXfer(buffersInput, readLenth, &ovLapStatus, context);

	    
		 ret =wResult && fResult;
		 if (ret != true)
		 {
			 CloseHandle(ovLapStatus.hEvent);
			 epBulkCmdIn->Abort();
			 epBulkOut->Abort();
			 //取消映射
			 if (rfile.IsOpen()) rfile.Close();
			 if (wfile.IsOpen()) wfile.Close();
			 pThis->pFormView3->RichEditShow(nThIdx, L"USB data req transfer err", COLOR_RED, 0, 0);
			 //关闭文件映射对象
			 pThis->m_pThreadUsbData[nThIdx] = NULL;
			 return -1;
		 }
		//OUT数据，主要流程，烧录校验
		if (buffersInput[0] == 'O')
		{
			cIs512Multy = buffersInput[1] & 4;
			memcpy(&writelenth, &buffersInput[2], 4);
			//0,1:SINGLE 和双BUFFER的STARTSTORE
			if ((buffersInput[1] & 3) <= 1)
			{
				if (cIs512Multy)
				{
					len= rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}

				}
				else
				{
					len=rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}

				//SN
				if ((cBufIdx & 0x7f) == BUFNUM)
				{
					pThis->m_CriticalSectionKey.Lock();
				//	pThis->pFormView3->RichEditShow(0, L"in 1 begin", COLOR_RED, 0, 0);
					//[0:3]第几组序列,低4位，,其余是OFFSET
					//[4]删除KEY文件吗
					//[5:31]OFFSET
					nSnChnIdx = llSeekAddr & 0xf;
					nNeedDelKey = ((llSeekAddr >> 4) & 1);
					nSnOfset = llSeekAddr >> 5;
					//取得几个序列号
					if (pThis->stu_GenSetting.nUserSnLen[nSnChnIdx])
					{
						int nSnCnt = writelenth / pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						writelenth = nSnCnt*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						if (writelenth > SIZE16MB - 1)
						{
							writelenth = SIZE2MB - 1;
							pThis->pFormView3->RichEditShow(nThIdx, L"change to 2MB(Key must <2MB)", COLOR_RED, 0, 0);
						}
						pThis->GetOneUserSn(nThIdx, nSnChnIdx, nSnOfset, nNeedDelKey, nSnCnt);
						pcData[0] = pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum;
						memcpy(pcData + 1, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr, writelenth);
						writelenth += 1;

					}
					else
					{
						writelenth = 2;
						memset(pcData, 0, writelenth);
					}
			//		pThis->pFormView3->RichEditShow(0, L"in 1 end", COLOR_RED, 0, 0);
					pThis->m_CriticalSectionKey.Unlock();
				}
				//等待三秒

				epBulkOut->XferData(pcData, writelenth);



			}

#if 1

			//下一次准备
			//memset(pcData, 1, 1024);
			//双buffer

			if ((buffersInput[1] & 2))
			{
				if (cIs512Multy)
				{
					len=rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}



				epBulkOut->XferData(pcData, writelenth);


			}
			//
#endif

		}
		//IN数据，读
		else if (buffersInput[0] == 'I')
		{
			if (wfile.IsClosed())
			{
				if (!wfile.Open(pThis->m_strReadFileDefaultPath[cwCurBufIdx], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
				{
					strtmp.Format(L"Failed to open the file %s\n", e.m_strFileName);
					AfxMessageBox(strtmp);
					epBulkCmdIn->Abort();
					epBulkOut->Abort();

					pThis->m_pThreadUsbData[nThIdx] = NULL;
					return 0;
				}
			}
			if (g_nIsEmmc){pThis->m_nIsLoadBufferDll = 1;pThis->m_nIsReadFitnessNeedDataAnalysis=1;}
			cBufIdx |= 0x80;
			len = wfile.GetPosition();
			//把读之前SEEK的位置加上去
			if (llSeekAddr > len)
			{
				//如果要填充1
				if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cwCurBufIdx & 0x7f], "0"))
				{
					memset(pSendbuf, 0xff, SIZE16MB);
					len = llSeekAddr - len;
					for (i = 0; i < len / SIZE16MB; i++)
					{
						wfile.Write(pSendbuf, SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
					}

					if (len%SIZE16MB)
					{
						wfile.Write(pSendbuf, len%SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
					}

				}
				else
				{
					//直接填0
					wfile.Seek(llSeekAddr, CFile64::begin, 1);
				}


			}

			memcpy(&readLenth, &buffersInput[2], 4);
			ret = epBulkIn->XferData(buffersInput, readLenth);
			if (ret != true)
			{
				CloseHandle(ovLapStatus.hEvent);
				epBulkCmdIn->Abort();
				epBulkOut->Abort();
				epBulkIn->Abort();
				//取消映射
				if (rfile.IsOpen()) rfile.Close();
				if (wfile.IsOpen()) wfile.Close();
				pThis->pFormView3->RichEditShow(nThIdx, L"USB data in transfer err", COLOR_RED, 0, 0);
				//关闭文件映射对象
				pThis->m_pThreadUsbData[nThIdx] = NULL;
				return -1;
			}
			wfile.Write(buffersInput, readLenth);
			nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(buffersInput, readLenth);
			nBufferIdxRd[cwCurBufIdx] = 1;
			len = wfile.GetPosition();
		}
		//正常结束和CANCEL
		else if (buffersInput[0] == 'C')
		{
			if (0 == buffersInput[2])
			{
				//正常退出

				if (0 == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
				{
					//socket号都不对
					pThis->m_nIsAuto[nThIdx] = 0;
					cStatus = PROC_SOCKETALLERR;
				}
				//读追加文件末尾填充
				if (cBufIdx & 0x80)
				{
					if (wfile.IsOpen())
					{
						len = wfile.GetPosition();
						sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f], "%x", &nBufDfLen);
						//要追加填充
						if (nBufDfLen > len)
						{
							//如果要填充1
							if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cBufIdx & 0x7f], "0"))
							{
								len = nBufDfLen - len;
								memset(pSendbuf, 0xff, SIZE16MB);
								for (i = 0; i < len / SIZE16MB; i++)
								{
									wfile.Write(pSendbuf, SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
								}

								if (len%SIZE16MB)
								{
									wfile.Write(pSendbuf, len%SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
								}

							}
							else
							{
								//直接填0
								wfile.Seek(nBufDfLen, CFile64::begin, 1);
							}

						}
					}
					
				}

				//if (cBufIdx & 0x80)
				{
					for (i = 0; i < BUFNUM; i++)
					{
						if (nBufferIdxRd[i])
						{
							CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);

							strtmp.Format(L"%s Checksum=0x%08x", wsztemp, nCheckSums[i]);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
							if (g_nIsEmmc)pThis->pFormView2->DispChecksumInListCtrl(pThis->m_cComboBufSelMap[i], nCheckSums[i], nCheckSums[i]);
						}
					}

				}

				
				goto PCEND;
			}
			//
			else if (1 == buffersInput[2])
			{
				//cancel
				//	strtmp.Format(L"Cancel thread %s\n", __FUNCTIONW__);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 0, pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit);
				pCProgress->SetPos(0);
				//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				cStatus = PROC_CANCEL;
				pThis->m_nIsAuto[nThIdx] = 0;
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				//pThis->Beep(nThIdx, 0);
				goto PCCANCEL;

			}
			//算法FAIL上报
			else if (2 == buffersInput[2])
			{
				//cancel
				strtmp.Format(L"Fail\n");
				pCProgress->SetPos(0);
				if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				cStatus = PROC_END;
			//	pThis->m_nIsAuto[nThIdx] = 0;
				goto PCEND;

			}

		}
		//DEBUGSTRING
		else if (buffersInput[0] == 'D')
		{
			if (0xff == ((UCHAR)buffersInput[2]))
			{
				int nColor = (buffersInput[3] << 16) | (buffersInput[4] << 8) | (buffersInput[5]);
				CharToTchar(wsztemp, (const char*)(buffersInput + 2 + 4));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, nColor, 0, 0);
			}
			else
			{
				CharToTchar(wsztemp, (const char*)(buffersInput + 2));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
			}


		}
		//进度条 PROGRESS
		else if (buffersInput[0] == 'P')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			pCProgress->SetPos(nScale);
			g_SerialResBuf[SERSOCKBASE + nSocketMax* 32 + (pThis->m_nSiteNo[nThIdx] - 1)] = nScale;

		}
		else if (buffersInput[0] == 'X')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			memcpy(g_ConfigData.nData, &buffersInput[2], 498);

		}
		//BufferSeek
		else if (buffersInput[0] == 'S')
		{

			memcpy(&nSeekL, &buffersInput[2], 4);
			memcpy(&wBufIdx8_Haddr8, &buffersInput[2 + 4], 2);
			llSeekAddr = (UINT64)(wBufIdx8_Haddr8 &0XFF)<< 32| nSeekL;
			cBufIdx = wBufIdx8_Haddr8 >> 8;

			//获得SN
			if ((cBufIdx & 0x7f) == BUFNUM)
			{

			}
			//写操作的BUFFER NUM与大于MAX
			else if(((cBufIdx & 0x7f) > BUFNUM) && ((cBufIdx & 0x80) == 0))
			{
				strtmp.Format(L"Buffer Idx>%d error\n", BUFNUM);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				pThis->Beep(nThIdx, 2);
				goto PCCANCEL;
			}

			//写操作时DEVICE没有这个BUFFER NUMBER
			else if (((cBufIdx & 0x80) == 0) && ((0 == strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[cBufIdx & 0x7f])) || (0 == strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f]))))
			{
				strtmp.Format(L"Buffer Idx %d Invalid\n", cBufIdx);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				goto PCCANCEL;
			}
			else if ((0 == (cBufIdx & 0x80)) && ((cBufIdx & 0X7F) == crCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是写操作

				rfile.Seek(llSeekAddr, CFile64::begin, 1);

			}
			else if ((cBufIdx & 0x80) && ((cBufIdx & 0X7F) == cwCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是读，啥也不干
			}
			//不同要重新打开文件
			else
			{
				//	if (Curfile.IsOpen())
				{
					//无论是否打开，当前读BUFFER idx都要更新
					cwCurBufIdx = cBufIdx & 0X7F;
					//读操作
					if (cBufIdx & 0x80)
					{
						if (wfile.IsOpen())
						{
							wfile.Close();
							strtmp.Format(L"wBuf%d closed", cwCurBufIdx);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
							
							//读直接用路径，不是BUFX
							path = pThis->m_strReadFileDefaultPath[cBufIdx & 0x7f];
							if (rfile.IsOpen())
							{
								if (rfile.GetFileName() == pThis->m_strReadFileDefaultPath[cwCurBufIdx])
								{
									rfile.Close();
								}
							}
							if (!wfile.Open(path, GENERIC_WRITE, 0, OPEN_ALWAYS, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								return 0;
							}
							//strtmp.Format(L"buf%d open,seek %d\n", cwCurBufIdx, llSeekAddr);
						}

					}
					//写操作
					else
					{
						if (rfile.IsOpen())
						{
							rfile.Close();
						//	strtmp.Format(L"wBuf%d closed", crCurBufIdx);
						//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
						}

							
						crCurBufIdx = cBufIdx & 0X7F;
						CharToTchar(wszPath, pstuDevInfo[g_curDeviceSel].szBufNameArrs[crCurBufIdx]);
						path.Format(L"%slib\\%s", g_wszCurPath, wszPath);
						path += L".bf";
						if (wfile.IsOpen())
						{
							if (wfile.GetFileName() == path)
							{
								wfile.Close();
							}
						}
						if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
						{
							strtmp.Format(L"Failed to open the file %s\n", e.m_strFileName);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
							CloseHandle(ovLapStatus.hEvent);
							return 0;
						}
						rfile.Seek(llSeekAddr, CFile64::begin, 1);
						//strtmp.Format(L"buf%d open,seek %d\n", crCurBufIdx, llSeekAddr);
						
					}


					//读的话，需要在读到数据的时候填充，不要直接SEEK，

				//	if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);

				}
			}

		}
		//LED状态显示颜色
		else if (buffersInput[0] == 'W')
		{
			memcpy(&nWarnLed, &buffersInput[2], 4);
			//pCProgress->SetPos(nScale);
			wColoridx = nWarnLed >> 16;
			//低16位是掩码

			if (WARNCOLOR_RED == wColoridx)
			{
				//有错误才显示红灯
				for (i = 0; i < nSocketMax; i++)
				{
					if (nWarnLed&(1 << i))
					{
						//重复SOCKET只显示一次
						if (0 == (wErrMaskinoneproc&(1 << i)))
						{
							if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
							{

								strtmp.Format(L"socket%d Failure", i + 1);
								if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 2);
							}

						}

					}
				}
				wErrMaskinoneproc |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_BLUE == wColoridx)
			{
				nNoticeBlue |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticeBlue&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_PURPLE == wColoridx)
			{
				nNoticePurple |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticePurple&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}

			else
			{
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nWarnLed&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}


		}

		if (ret != true)
		{
			pThis->stu_UsbDeviceArr[nThIdx].status = USBNOTCONNECT;

			//SOCKET设置未连接
			g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = USBNOTCONNECT;
			memset(&g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax], SER_SOCKET_DISABLE, nSocketMax);
			memset(&pThis->stu_AutoSeq[nThIdx], 0, sizeof(pThis->stu_AutoSeq[nThIdx]));
			cStatus = PROC_ERRSTOP;
			goto USBERR;

		}

	}

PCEND:
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	//如果选了叠料
	if (pThis->stu_overlap.nIsOverLapCheck[nThIdx])
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Checking", COLOR_YELLOW, 0, 0);
		wErrMaskinoneproc = (~(wErrMaskinoneproc))&(pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
		pThis->stu_overlap.nOverLapSockFail[nThIdx] = wErrMaskinoneproc;

		pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, pThis->stu_overlap.nOverLapSockFail[nThIdx]);
		//如果校验成功，代表叠料了

		if(pThis->stu_overlap.nOverLapSockFail[nThIdx])
		{
			if (pThis->stu_overlap.nOverLapSockFail[nThIdx] == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Check Fail", COLOR_RED, 0, 0);
				
			}
			for (i = 0; i < SOCKETMAX; i++)
			{
				if((1<<i)&(pThis->stu_overlap.nOverLapSockFail[nThIdx] ))
				{
					strtmp.Format(L"Sok %d overlap Fail", i + 1);
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				}
			}
			
		}
		
	}
		
	//如果选了空检查出错擦除，第一步是空检查，都OK的情况下，直接跳过下面的ERASE
	else if((pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'b')&&(g_nEraseWhenNOTBlank))
	{
		if(wErrMaskinoneproc==0)
		{
			pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;						
		}
		//g_nEraseWhenNOTBlank==1在BLANK中ERRMASK不能设置1，否则会导致后面退出
		wErrMaskinoneproc = 0;

	}
	
	//全错，又不是blank且g_nEraseWhenNOTBlank=0，则停止
	if (wErrMaskinoneproc == pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)
	{
		pThis->m_nIsAuto[nThIdx] = 0;
	}
PCCANCEL:
	pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus |= (wErrMaskinoneproc|pThis->stu_overlap.nOverLapSockFail[nThIdx]);

	
	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
USBERR:
	epBulkCmdIn->Abort();
	epBulkOut->Abort();
	CloseHandle(ovLapStatus.hEvent);

	//取消映射
	if (rfile.IsOpen())
		rfile.Close();
	if (wfile.IsOpen())
	{
		wfile.Close();
	}
	

	//关闭文件映射对象

	pThis->m_pThreadUsbData[nThIdx] = NULL;

	if (cStatus == PROC_CANCEL)
	{
		strtmp.Empty();
	}
	//如果SOCKET全部报错。就不报下面这些FINISHED了
	if (cStatus != PROC_SOCKETALLERR)
	{
		if (cStatus == PROC_CANCEL)strtmp += L" Canceled";
		else
		{
			if (0 == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" SUCCESS";;
			}
			else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" FAIL";
			}
			else
				strtmp += L" FINISHED"; 
		}
		if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 6);
		TimeEnd = CTime::GetCurrentTime();
		Timedif = TimeEnd - TimeBegin;
		delay = Timedif.GetMinutes() * 60 + Timedif.GetSeconds();
		strtmp.Format(L"%d seconds", delay);
		pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
	}

	if ((cStatus == PROC_END) || (cStatus == PROC_CANCEL))
	{
		//AUTO中
		if (pThis->m_nIsAuto[nThIdx])
		{
			//叠料检测那次不++；
			if (pThis->stu_overlap.nIsOverLapCheck[nThIdx] == 0)
			{
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;
				
			}
			else pThis->stu_overlap.nIsOverLapCheck[nThIdx] = 0;

		PRESSURElOOP:


			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx < pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				//中途掉线就不AUTO哦了
				if (pThis->stu_UsbDeviceArr[nThIdx].status != USBNOTCONNECT)
					AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap1, (LPVOID)pThis);
			}
			//在AUTO中的最后一次
			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
			}
		}
		//单次或者AUTO最后一次
		if (pThis->m_nIsAuto[nThIdx] == 0)
		{
			//记录本次失败的SOCKET
			pThis->m_FailSktLastAuto[nThIdx] = wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
			if (pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				if (0xff == (pThis->m_nBtnIdx & 0xff))
				{//确保是AUTO
					if (0 == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO SUCCESS";
					}
					else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO FAIL";
					}
					else
						strtmp = L"AUTO FINISHED";
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
				}
			}
			//统计
			for (i = 0; i < nSocketMax; i++)
			{
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{

					if ((wErrMaskinoneproc|pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus)&(1 << i))
					{

						pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[i]++;
						pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt++;
					}
					pThis->stu_UsbDeviceArr[nThIdx].nSokTotalCnt[i]++;
					pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt++;
				}
			}
			strtmp.Format(L"Total:%d  Success:%d  Fail:%d", pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt - pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 40);
			strtmp.Format(L"SockFail %d,%d,%d,%d,%d,%d,%d,%d", pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[0], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[1], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[2], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[3], \
				pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[4], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[5], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[6], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[7]);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 0);
			pThis->SummaryLog(nThIdx);
			//根据nSockProgStatus ,失败的写回SN 文件
			//if (nNeedDelKey)
			{
				for (nSnChnIdx = 0; nSnChnIdx < pThis->stu_GenSetting.nCnt; nSnChnIdx++)
				{
					if (pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum > 0)
					{
						idx = 0;
						pThis->m_CriticalSectionLog.Lock();
						for (i = 0; i < SOCKETMAX; i++)
						{
							//SOCKET不为空
							if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit&(1 << i))
							{
								//失败，SN码一一写回
								//失败，从KEYPSD文件夹MOVEBACK
								//char path_buffer[_MAX_PATH];
								TCHAR drive[_MAX_DRIVE];
								TCHAR dir[_MAX_DIR];
								TCHAR fname[_MAX_FNAME];
								TCHAR ext[_MAX_EXT];
								_wsplitpath(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], drive, dir, fname, ext);
								if (pThis->stu_GenSetting.nIsDelete)
								{
									strtmp = g_wszCurPath;
								}
								else
								{
									strtmp = drive;
									strtmp += dir;
								}
								strtmp += L"KPsd\\";
								strtmp += fname;
								strtmp += ext;
								if (0 != (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i)))
								{

								}
								else
								{	
									DeleteFile(strtmp);
									if (0 == MoveFile(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], strtmp))
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										strtmp += L" move fail";
										pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

									}
									else
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										if (wcslen(fname))
										{

											strtmp += L" moved";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
										//	pThis->m_CriticalSectionLog.Lock();
											if (pThis->stu_GenSetting.nIsDelete)
											{
												strtmp = g_wszCurPath;
											}
											else
											{
												strtmp = drive;
												strtmp += dir;
											}

											strtmp += L"KPsd\\";
											
										//	pThis->pFormView3->RichEditShow(0, L"1 log begin", COLOR_PINK_CLEAR, 0, 0);
											//pThis->pFormView3->RichEditShow(0, fname, COLOR_YELLOW, 0, 0);
											pThis->logPsdKey1(strtmp, fname);
										//	pThis->pFormView3->RichEditShow(0, L"1 log end", COLOR_PINK_CLEAR, 0, 0);
										//	pThis->m_CriticalSectionLog.Unlock();
										}
									}
									
								}
								idx++;

							}
						}
						pThis->m_CriticalSectionLog.Unlock();
					}

				}
			}
			
			if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				//全错 FAIL


				pThis->Beep(nThIdx, 2);


			}
			//成功，无错
			else if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->Beep(nThIdx, 0);
			}
			//计算时间
			if (cStatus != PROC_SOCKETALLERR)
			{
				pThis->m_TimeEnd[nThIdx] = CTime::GetCurrentTime();
				Timedif = pThis->m_TimeEnd[nThIdx] - pThis->m_TimeBegin[nThIdx];
				delay = Timedif.GetTotalSeconds();
				strtmp.Format(L"Total %d seconds", delay);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
				pThis->pFormView3->RichEditShow(nThIdx, L"", OPERATIONCOLOR, 0, 0);
			}

			//删除KEY的记录
			for (i = 0; i < 10; i++)
			{
				pThis->stu_UserSNProg[nThIdx][i].nSnNum = 0;
				memset(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile, 0, sizeof(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile));
			}
			pThis->HighZ_CloseV(nThIdx);
		}
	}
	if (pThis->m_nIsAuto[nThIdx] == 0)
	{
		//串口 和网络
		if ((stu_RemoteStat.nRemoteStat > 0) && ((TRUE == stu_RemoteStat.isComOpened) || (pThis->m_SocketObject.IsOpen())))
		{

			for (i = 0; i < nSocketMax; i++)
			{
				//使能的SOCKET都RUN
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{
					//失败的
					if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i))
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
					//成功的
					else
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_OK;
					}

				}

				//未使能的，如果是SOCKET ERR=1，是座子号不对
				else
				{
				//	if (pThis->stu_UsbDeviceArr[nThIdx].cSokEncRet[i])
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
				}

			}

			g_SerialResBuf[(pThis->m_nSiteNo[nThIdx] - 1)] = SER_PROG_READY;

		}
		pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus = 0;
	}



	pThis->pFormView1->CntDisplayEachLeftListCtrl(nThIdx, 0);
	pThis->pFormView2->CntDisplayEachPanel(nThIdx);


	//压力测试
	//如果选择PINCHECK AUTO，使用压力测试的流程，把次数固定
	if (pThis->nAutoSenseAutoRun)
	{
		if (pThis->nAutoSenseAutoRunStartEnd % 2)
		{
			pThis->m_nAutoCntPressure[nThIdx] = 5;
		}
		else
		{
			pThis->m_nAutoCntPressure[nThIdx] = 0;
			pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
			pThis->nAutoSenseAutoRunStartEnd = 0;
			pThis->m_pThreadUsbData[nThIdx] = NULL;

		}

	}
	if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
	{
		if (pThis->m_nAutoCntPressure[nThIdx] > 0)
		{
			nSocketMax = 0;
			pThis->m_nAutoCntPressure[nThIdx]--;
			if (pThis->m_nAutoCntPressure[nThIdx] > 0)
			{
				pThis->m_nIsAuto[nThIdx] = 0xff;
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx = 0;

				goto PRESSURElOOP;
			}
		}
	}
	return 0;
}


UCHAR gSendbuf2[16 * 1024 * 1024];
UCHAR gReadbuf2[4 * 1024 * 1024];

//四个MAP不同之处
//pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread0, (LPVOID)pThis);
//AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap0, (LPVOID)pThis);
//PRESSURElOOP
//PCEND
//PCCANCEL
//USBERR
DWORD WINAPIV CMainFrame::UsbDataProcFileMap2(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR *pSendbuf = gSendbuf2;
	UCHAR *pReadbuf = gReadbuf2;
	CProgressCtrl *pCProgress = &pThis->pFormView2->m_progress2;

	CTimeSpan Timedif;
	int delay;
	CTime TimeBegin = CTime::GetCurrentTime();
	CTime TimeEnd;
	int len;
	int nThIdx = 2;
	int nBufDfLen;
	TCHAR wszPath[MAX_PATH];
	int nNeedDelKey = 0;
	TCHAR wsztemp[180];
	UINT nSnOfset;
	BYTE inEpAddress = 0x83, outEpAddress = 0x01;
	UCHAR cStatus = PROC_END;
	int base = 0;
	UINT *pInt;
	bool ret = 0;
	CString strtmp, showstr = L"";
	PUCHAR		buffersInput = pReadbuf;
	CCyUSBEndPoint *epBulkOut = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(outEpAddress);
	CCyUSBEndPoint *epBulkIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(0X81);
	CCyUSBEndPoint *epBulkCmdIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(inEpAddress);
	long writelenth = 0;
	long nWarnLed = 0;
	long nScale = 0;
	UCHAR *pcData;
	UINT checksum = 0;
	UINT nCheckSums[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	UINT nBufferIdxRd[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
	long readLenth = 1024 * 1024;
	short wColoridx;
	int wErrMaskinoneproc = 0;
	int nNoticeBlue = 0;
	int nNoticePurple = 0;
	UINT64 llSeekAddr = 0;
	//最高位是1表示是读的BUF.
	UCHAR cBufIdx = 0;
	UCHAR  crCurBufIdx = 0;
	UCHAR  cwCurBufIdx = 0;
	UINT nSeekL = 0;
	USHORT wBufIdx8_Haddr8 = 0;
	if (epBulkOut == NULL || epBulkCmdIn == NULL || epBulkIn == NULL) return 1;
	int i, idx = 0;
	int nSocketSenseMask = 0;
	INT nSocketMax = SOCKETMAX;
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		nSocketMax = 2 * SOCKETMAX;


	for (i = 0; i < nSocketMax; i++)
	{
		//使能的SOCKET都RUN
		if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_RUN;
		}
		else
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_DISABLE;
		}

	}



	g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = SER_PROG_RUNNING;


	int nBtnIdx;
	Sleep(THDLY);
	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_RUN;


	if (0 == pThis->nAutoSenseAutoRun)
	{
		//没选autosense
	//单步或者AUTO 第一步,才需要下载算法。FPGA等。AUTO的后面几步就不需要了//叠料//非空擦除第一次擦除
		if ((pThis->m_nIsAuto[nThIdx] == 0) || ((pThis->m_nIsAuto[nThIdx]) && (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0)) || pThis->stu_overlap.nIsOverLapCheck[nThIdx] ||
			(g_nEraseWhenNOTBlank && ('e' == pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]])))
		{
			ret = pThis->DownloadConfig_GetPincheck(nThIdx);
		}
	}

	else
	{
		//选了AUTOsense，第一次要DownloadConfig_GetPincheck0，之后每个AUTO的第一次只要要SendConfiWord就行
		if ((pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0) || (0 == pThis->nAutoLoopFirst[nThIdx]))
		{
			pThis->pFormView3->RichEditShow(nThIdx, L"Please insert new chips.....", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 20);
			while (1)
			{

				if (0 == pThis->nAutoLoopFirst[nThIdx])
				{
					ret = pThis->DownloadConfig_GetPincheck(nThIdx);
					if (ret)break;

				}
				else
				{
					ret = pThis->SendConfiWord(nThIdx, 3, pThis->m_cDownData[nThIdx], sizeof(pThis->m_cDownData[nThIdx]));
					if (ret)break;
				}
				pThis->PinSenseInAuto(nThIdx, pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
				pThis->pFormView2->SenseBlink(nThIdx);
				for (i = 0; i < SOCKETMAX; i++)
				{
					if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit & (1 << i))
					{
						//第一次接触上就行
						if (pThis->nAutoLoopFirst[nThIdx])
						{
							if (BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}
						else
						{
							//之后要有状态便话，有先取再放的过程
							if ((BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]) || (BLINK_NULL == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]))
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}

					}
				}
				pThis->nAutoLoopFirst[nThIdx] = 1;
				if (nSocketSenseMask == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)break;
				//停止
				if (0 == (pThis->nAutoSenseAutoRunStartEnd % 2))
				{

					memset(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx]));
					//	memset(stu_PinCheckBlink.nStartBlinkArr[i], 0, sizeof(stu_PinCheckBlink.nStartBlinkArr[i]));
					memset(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx]));
					pThis->m_nAutoCntPressure[nThIdx] = 0;
					pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
					pThis->m_pThreadUsbData[nThIdx] = NULL;
					pThis->nAutoSenseAutoRunStartEnd = 0;
					pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
					for (i = 0; i < SOCKETMAX; i++)
					{
						if (BLINK_START == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
						{
							pThis->pFormView2->mp_Static_ModArr[nThIdx][i]->SetIcon(pThis->pFormView2->stu_PinCheckBlink.HiconsavedIcon[nThIdx][i]);
						}
					}
					return 0;

				}
			}
		}
	}
	if (ret)
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		return 0;
	}
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	strtmp += L" BEGIN...";
	pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 30);

	//OVERLAPPED		OutOvLap;
	//UCHAR *outContext;
	//延续上次的错误状态码
	wErrMaskinoneproc |= pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus;
	//传输数据是否512字节的倍数，要处理，否则，传输死机
	char cIs512Multy = 0;



	CString path;
	CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[0]);
	path.Format(L"%slib\\%s", g_wszCurPath, wsztemp);
	path += L".bf";
	//创建文件对象
	CFileException e;
	CFile64 wfile;
	CFile64 rfile;
	int nSnChnIdx = 0;
	CFile SnFile;


	//如果是读.开读的文件
	if (pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'r')
	{
	/*	if (!wfile.Open(pThis->m_strReadFileDefaultPath[0], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

			return 0;
		}*/
	}
	strtmp = path;
	showstr = pThis->m_strReadFileDefaultPath[0];
	//if (strtmp.MakeUpper() != showstr.MakeUpper())
	{
		if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
			return 0;
		}
	}
	strtmp.Empty();
	showstr.Empty();



	//要注意的是,必须先操作完 pBuffer才能UnmapViewOfFile,
	//如果先UnmapViewOfFile,再操作 pBuffer则会出错,因为pBuffer已经被释放了
	pInt = (UINT*)pSendbuf;
	pcData = (UCHAR *)pSendbuf;

	epBulkOut->Abort();
	epBulkOut->Reset();
	epBulkCmdIn->Abort();
	epBulkCmdIn->Reset();
	epBulkIn->Abort();
	epBulkIn->Reset();

	//strtmp.Format(L"checksum=%u\n", checksum);
	pCProgress->SetRange(0, 100);
	epBulkOut->TimeOut = INFINITE;
	epBulkCmdIn->TimeOut = INFINITE;
	checksum = 0;


	//面板LED显示

	if (pThis->m_pThreadUserProc1[nThIdx] != NULL)
	{
		strtmp.Format(L"site%d thread proc ptr NOT NULL", pThis->m_nSiteNo[nThIdx]);
		AfxMessageBox(strtmp);
	}
	OVERLAPPED ovLapStatus;
	memset(&ovLapStatus, 0, sizeof(OVERLAPPED));
	ovLapStatus.hEvent = CreateEvent(NULL, false, false, NULL);
	int nMutex = 0;
	while (1)
	{
	
	
	 
	   

	    
		
		PUCHAR context = epBulkCmdIn->BeginDataXfer(buffersInput, readLenth, &ovLapStatus);
		if (nMutex == 0)
		{
			nMutex = 1;
			pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread, (LPVOID)&nThIdx);
		}
		
		bool   wResult = epBulkCmdIn->WaitForXfer(&ovLapStatus,INFINITE);
		bool   fResult = epBulkCmdIn->FinishDataXfer(buffersInput, readLenth, &ovLapStatus, context);

	    
		 ret =wResult && fResult;
		 if (ret != true)
		 {
			 CloseHandle(ovLapStatus.hEvent);
			 epBulkCmdIn->Abort();
			 epBulkOut->Abort();
			 //取消映射
			 if (rfile.IsOpen()) rfile.Close();
			 if (wfile.IsOpen()) wfile.Close();
			 pThis->pFormView3->RichEditShow(nThIdx, L"USB data req transfer err", COLOR_RED, 0, 0);
			 //关闭文件映射对象
			 pThis->m_pThreadUsbData[nThIdx] = NULL;
			 return -1;
		 }
		//OUT数据，主要流程，烧录校验
		if (buffersInput[0] == 'O')
		{
			cIs512Multy = buffersInput[1] & 4;
			memcpy(&writelenth, &buffersInput[2], 4);
			//0,1:SINGLE 和双BUFFER的STARTSTORE
			if ((buffersInput[1] & 3) <= 1)
			{
				if (cIs512Multy)
				{
					len=rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}

				//SN
				if ((cBufIdx & 0x7f) == BUFNUM)
				{
					pThis->m_CriticalSectionKey.Lock();
					//[0:3]第几组序列,低4位，,其余是OFFSET
					//[4]删除KEY文件吗
					//[5:31]OFFSET
					nSnChnIdx = llSeekAddr & 0xf;
					nNeedDelKey = ((llSeekAddr >> 4) & 1);
					nSnOfset = llSeekAddr >> 5;
					//取得几个序列号
					if (pThis->stu_GenSetting.nUserSnLen[nSnChnIdx])
					{
						int nSnCnt = writelenth / pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						writelenth = nSnCnt*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						if (writelenth > SIZE16MB - 1)
						{
							writelenth = SIZE2MB - 1;
							pThis->pFormView3->RichEditShow(nThIdx, L"change to 2MB(Key must <2MB)", COLOR_RED, 0, 0);
						}
						pThis->GetOneUserSn(nThIdx, nSnChnIdx, nSnOfset, nNeedDelKey, nSnCnt);
						pcData[0] = pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum;
						memcpy(pcData + 1, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr, writelenth );
						writelenth += 1;
					}
					else
					{
						writelenth = 2;
						memset(pcData, 0, writelenth);
					}

					pThis->m_CriticalSectionKey.Unlock();
				}
				//等待三秒

				epBulkOut->XferData(pcData, writelenth);



			}

#if 1

			//下一次准备
			//memset(pcData, 1, 1024);
			//双buffer

			if ((buffersInput[1] & 2))
			{
				if (cIs512Multy)
				{
					len=rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}
				


				epBulkOut->XferData(pcData, writelenth);


			}
			//
#endif

		}
		//IN数据，读
		else if (buffersInput[0] == 'I')
		{
			if (wfile.IsClosed())
			{
				if (!wfile.Open(pThis->m_strReadFileDefaultPath[cwCurBufIdx], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
				{
					strtmp.Format(L"Failed to open the file %s\n", e.m_strFileName);
					AfxMessageBox(strtmp);
					epBulkCmdIn->Abort();
					epBulkOut->Abort();

					pThis->m_pThreadUsbData[nThIdx] = NULL;
					return 0;
				}
			}
			if (g_nIsEmmc){pThis->m_nIsLoadBufferDll = 1;pThis->m_nIsReadFitnessNeedDataAnalysis=1;}
			cBufIdx |= 0x80;
			len = wfile.GetPosition();
			//把读之前SEEK的位置加上去
			if (llSeekAddr > len)
			{
				//如果要填充1
				if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cwCurBufIdx & 0x7f], "0"))
				{
					memset(pSendbuf, 0xff, SIZE16MB);
					len = llSeekAddr - len;
					for (i = 0; i < len / SIZE16MB; i++)
					{
						wfile.Write(pSendbuf, SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
					}

					if (len%SIZE16MB)
					{
						wfile.Write(pSendbuf, len%SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
					}

				}
				else
				{
					//直接填0
					wfile.Seek(llSeekAddr, CFile64::begin, 1);
				}


			}

			memcpy(&readLenth, &buffersInput[2], 4);
			ret = epBulkIn->XferData(buffersInput, readLenth);
			if (ret != true)
			{
				CloseHandle(ovLapStatus.hEvent);
				epBulkCmdIn->Abort();
				epBulkOut->Abort();
				epBulkIn->Abort();
				//取消映射
				if (rfile.IsOpen()) rfile.Close();
				if (wfile.IsOpen()) wfile.Close();
				pThis->pFormView3->RichEditShow(nThIdx, L"USB data in transfer err", COLOR_RED, 0, 0);
				//关闭文件映射对象
				pThis->m_pThreadUsbData[nThIdx] = NULL;
				return -1;
			}
			wfile.Write(buffersInput, readLenth);
			nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(buffersInput, readLenth);
			nBufferIdxRd[cwCurBufIdx] = 1;
			len = wfile.GetPosition();
		}
		//正常结束和CANCEL
		else if (buffersInput[0] == 'C')
		{
			if (0 == buffersInput[2])
			{
				//正常退出

				if (0 == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
				{
					//socket号都不对
					pThis->m_nIsAuto[nThIdx] = 0;
					cStatus = PROC_SOCKETALLERR;
				}
				//读追加文件末尾填充
				if (cBufIdx & 0x80)
				{
					if (wfile.IsOpen())
					{
						len = wfile.GetPosition();
						sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f], "%x", &nBufDfLen);
						//要追加填充
						if (nBufDfLen > len)
						{
							//如果要填充1
							if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cBufIdx & 0x7f], "0"))
							{
								len = nBufDfLen - len;
								memset(pSendbuf, 0xff, SIZE16MB);
								for (i = 0; i < len / SIZE16MB; i++)
								{
									wfile.Write(pSendbuf, SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
								}

								if (len%SIZE16MB)
								{
									wfile.Write(pSendbuf, len%SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
								}

							}
							else
							{
								//直接填0
								wfile.Seek(nBufDfLen, CFile64::begin, 1);
							}

						}
					}
					
				}

				//if (cBufIdx & 0x80)
				{
					for (i = 0; i < BUFNUM; i++)
					{
						if (nBufferIdxRd[i])
						{
							CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);

							strtmp.Format(L"%s Checksum=0x%08x", wsztemp, nCheckSums[i]);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
							if (g_nIsEmmc)pThis->pFormView2->DispChecksumInListCtrl(pThis->m_cComboBufSelMap[i], nCheckSums[i], nCheckSums[i]);
						}
					}

				}


				goto PCEND;
			}
			//
			else if (1 == buffersInput[2])
			{
				//cancel
				//	strtmp.Format(L"Cancel thread %s\n", __FUNCTIONW__);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 0, pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit);
				pCProgress->SetPos(0);
				//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				cStatus = PROC_CANCEL;
				pThis->m_nIsAuto[nThIdx] = 0;
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				//pThis->Beep(nThIdx, 0);;
				goto PCCANCEL;

			}
			//算法FAIL上报
			else if (2 == buffersInput[2])
			{
				//cancel
				strtmp.Format(L"Fail\n");
				pCProgress->SetPos(0);
				if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				cStatus = PROC_END;
			//	pThis->m_nIsAuto[nThIdx] = 0;
				goto PCEND;

			}

		}
		//DEBUGSTRING
		else if (buffersInput[0] == 'D')
		{
			if (0xff == ((UCHAR)buffersInput[2]))
			{
				int nColor = (buffersInput[3] << 16) | (buffersInput[4] << 8) | (buffersInput[5]);
				CharToTchar(wsztemp, (const char*)(buffersInput + 2 + 4));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, nColor, 0, 0);
			}
			else
			{
				CharToTchar(wsztemp, (const char*)(buffersInput + 2));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
			}


		}
		//进度条 PROGRESS
		else if (buffersInput[0] == 'P')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			pCProgress->SetPos(nScale);
			g_SerialResBuf[SERSOCKBASE + nSocketMax* 32 + (pThis->m_nSiteNo[nThIdx] - 1)] = nScale;
		}
		else if (buffersInput[0] == 'X')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			memcpy(g_ConfigData.nData, &buffersInput[2], 498);

		}
		//BufferSeek
		else if (buffersInput[0] == 'S')
		{

			memcpy(&nSeekL, &buffersInput[2], 4);
			memcpy(&wBufIdx8_Haddr8, &buffersInput[2 + 4], 2);
			llSeekAddr = (UINT64)(wBufIdx8_Haddr8 &0XFF)<< 32| nSeekL;
			cBufIdx = wBufIdx8_Haddr8 >> 8;

			//获得SN
			if ((cBufIdx & 0x7f) == BUFNUM)
			{

			}
			//写操作的BUFFER NUM与大于MAX
			else if (((cBufIdx & 0x7f) > BUFNUM) && ((cBufIdx & 0x80) == 0))
			{
				strtmp.Format(L"Buffer Idx>%d error\n", BUFNUM);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				pThis->Beep(nThIdx, 2);
				goto PCCANCEL;
			}

			//写操作时DEVICE没有这个BUFFER NUMBER
			else if (((cBufIdx & 0x80) == 0) && ((0 == strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[cBufIdx & 0x7f])) || (0 == strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f]))))
			{
				strtmp.Format(L"Buffer Idx %d Invalid\n", cBufIdx);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				goto PCCANCEL;
			}
			else if ((0 == (cBufIdx & 0x80)) && ((cBufIdx & 0X7F) == crCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是写操作

				rfile.Seek(llSeekAddr, CFile64::begin, 1);

			}
			else if ((cBufIdx & 0x80) && ((cBufIdx & 0X7F) == cwCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是读，啥也不干
			}
			//不同要重新打开文件
			else
			{
				//	if (Curfile.IsOpen())
				{
					//无论是否打开，当前读BUFFER idx都要更新
					cwCurBufIdx = cBufIdx & 0X7F;
					//读操作
					if (cBufIdx & 0x80)
					{
						if (wfile.IsOpen())
						{
							wfile.Close();
							strtmp.Format(L"wBuf%d closed", cwCurBufIdx);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
							
							//读直接用路径，不是BUFX
							path = pThis->m_strReadFileDefaultPath[cBufIdx & 0x7f];
							if (rfile.IsOpen())
							{
								if (rfile.GetFileName() == pThis->m_strReadFileDefaultPath[cwCurBufIdx])
								{
									rfile.Close();
								}
							}
							if (!wfile.Open(path, GENERIC_WRITE, 0, OPEN_ALWAYS, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								return 0;
							}
							strtmp.Format(L"buf%d open,seek %d\n", cwCurBufIdx, llSeekAddr);
						}

					}
					//写操作
					else
					{
						if (rfile.IsOpen())
						{
							rfile.Close();
							//strtmp.Format(L"wBuf%d closed", crCurBufIdx);
							//pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
						}
							crCurBufIdx = cBufIdx & 0X7F;
							CharToTchar(wszPath, pstuDevInfo[g_curDeviceSel].szBufNameArrs[crCurBufIdx]);
							path.Format(L"%slib\\%s", g_wszCurPath, wszPath);
							path += L".bf";
							if (wfile.IsOpen())
							{
								if (wfile.GetFileName() == path)
								{
									wfile.Close();
								}
							}
							if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								return 0;
							}
							rfile.Seek(llSeekAddr, CFile64::begin, 1);
							strtmp.Format(L"buf%d open,seek %d\n", crCurBufIdx, llSeekAddr);
						
					}


					//读的话，需要在读到数据的时候填充，不要直接SEEK，

				//	if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);

				}
			}

		}
		//LED状态显示颜色
		else if (buffersInput[0] == 'W')
		{
			memcpy(&nWarnLed, &buffersInput[2], 4);
			//pCProgress->SetPos(nScale);
			wColoridx = nWarnLed >> 16;
			//低16位是掩码

			if (WARNCOLOR_RED == wColoridx)
			{
				//有错误才显示红灯
				for (i = 0; i < nSocketMax; i++)
				{
					if (nWarnLed&(1 << i))
					{
						//重复SOCKET只显示一次
						if (0 == (wErrMaskinoneproc&(1 << i)))
						{
							if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
							{

								strtmp.Format(L"socket%d Failure", i + 1);
								if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 2);
							}

						}

					}
				}
				wErrMaskinoneproc |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_BLUE == wColoridx)
			{
				nNoticeBlue |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticeBlue&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_PURPLE == wColoridx)
			{
				nNoticePurple |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticePurple&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}

			else
			{
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nWarnLed&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}


		}

		if (ret != true)
		{
			pThis->stu_UsbDeviceArr[nThIdx].status = USBNOTCONNECT;

			//SOCKET设置未连接
			g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = USBNOTCONNECT;
			memset(&g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax], SER_SOCKET_DISABLE, nSocketMax);
			memset(&pThis->stu_AutoSeq[nThIdx], 0, sizeof(pThis->stu_AutoSeq[nThIdx]));
			cStatus = PROC_ERRSTOP;
			goto USBERR;

		}

	}

PCEND:
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	//如果选了叠料
	if (pThis->stu_overlap.nIsOverLapCheck[nThIdx])
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Checking", COLOR_YELLOW, 0, 0);
		wErrMaskinoneproc = (~(wErrMaskinoneproc))&(pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
		pThis->stu_overlap.nOverLapSockFail[nThIdx] = wErrMaskinoneproc;

		pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, pThis->stu_overlap.nOverLapSockFail[nThIdx]);
		//如果校验成功，代表叠料了

		if(pThis->stu_overlap.nOverLapSockFail[nThIdx])
		{
			if (pThis->stu_overlap.nOverLapSockFail[nThIdx] == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Check Fail", COLOR_RED, 0, 0);
				
			}
			for (i = 0; i < SOCKETMAX; i++)
			{
				if((1<<i)&(pThis->stu_overlap.nOverLapSockFail[nThIdx] ))
				{
					strtmp.Format(L"Sok %d overlap Fail", i + 1);
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				}
			}
			
		}
		
	}
		
	//如果选了空检查出错擦除，第一步是空检查，都OK的情况下，直接跳过下面的ERASE
	else if((pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'b')&&(g_nEraseWhenNOTBlank))
	{
		if(wErrMaskinoneproc==0)
		{
			pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;						
		}
		//g_nEraseWhenNOTBlank==1在BLANK中ERRMASK不能设置1，否则会导致后面退出
		wErrMaskinoneproc = 0;

	}
	
	//全错，又不是blank且g_nEraseWhenNOTBlank=0，则停止
	if (wErrMaskinoneproc == pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)
	{
		pThis->m_nIsAuto[nThIdx] = 0;
	}
PCCANCEL:
	pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus |= (wErrMaskinoneproc|pThis->stu_overlap.nOverLapSockFail[nThIdx]);


	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
USBERR:
	CloseHandle(ovLapStatus.hEvent);
	epBulkCmdIn->Abort();
	epBulkOut->Abort();
	//CloseHandle(OutOvLap.hEvent);
	//取消映射
	if (rfile.IsOpen())
		rfile.Close();
	if (wfile.IsOpen())
	{
		wfile.Close();
	}
	

	//关闭文件映射对象

	pThis->m_pThreadUsbData[nThIdx] = NULL;

	if (cStatus == PROC_CANCEL)
	{
		strtmp.Empty();
	}
	//如果SOCKET全部报错。就不报下面这些FINISHED了
	if (cStatus != PROC_SOCKETALLERR)
	{
		if (cStatus == PROC_CANCEL)strtmp += L" Canceled";
		else
		{
			if (0 == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" SUCCESS";;
			}
			else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" FAIL";
			}
			else
				strtmp += L" FINISHED";
		}
		if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 6);
		TimeEnd = CTime::GetCurrentTime();
		Timedif = TimeEnd - TimeBegin;
		delay = Timedif.GetMinutes() * 60 + Timedif.GetSeconds();
		strtmp.Format(L"%d seconds", delay);
		pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
	}

	if ((cStatus == PROC_END) || (cStatus == PROC_CANCEL))
	{
		//AUTO中
		if (pThis->m_nIsAuto[nThIdx])
		{
			//叠料检测那次不++；
			if (pThis->stu_overlap.nIsOverLapCheck[nThIdx] == 0)
			{
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;
				
			}
			else pThis->stu_overlap.nIsOverLapCheck[nThIdx] = 0;


		PRESSURElOOP:


			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx < pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				//中途掉线就不AUTO哦了
				if (pThis->stu_UsbDeviceArr[nThIdx].status != USBNOTCONNECT)
					AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap2, (LPVOID)pThis);
			}
			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
			}
		}
		//单次或者AUTO最后一次
		if (pThis->m_nIsAuto[nThIdx] == 0)
		{
			//记录本次失败的SOCKET
			pThis->m_FailSktLastAuto[nThIdx] = wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
			if (pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				if (0xff == (pThis->m_nBtnIdx & 0xff))
				{//确保是AUTO
					if (0 == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO SUCCESS";
					}
					else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO FAIL";
					}
					else
						strtmp = L"AUTO FINISHED";
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
				}
			}
			//统计
			for (i = 0; i < nSocketMax; i++)
			{
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{

					if ((wErrMaskinoneproc|pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus)&(1 << i))
					{

						pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[i]++;
						pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt++;
					}
					pThis->stu_UsbDeviceArr[nThIdx].nSokTotalCnt[i]++;
					pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt++;
				}
			}
			strtmp.Format(L"Total:%d  Success:%d  Fail:%d", pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt - pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 40);
			strtmp.Format(L"SockFail %d,%d,%d,%d,%d,%d,%d,%d", pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[0], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[1], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[2], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[3], \
				pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[4], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[5], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[6], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[7]);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 0);
			pThis->SummaryLog(nThIdx);
			//if (nNeedDelKey)
			{
				for (nSnChnIdx = 0; nSnChnIdx < pThis->stu_GenSetting.nCnt; nSnChnIdx++)
				{
					if (pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum > 0)
					{
						idx = 0;
						pThis->m_CriticalSectionLog.Lock();
						for (i = 0; i < SOCKETMAX; i++)
						{
							//SOCKET不为空
							if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit&(1 << i))
							{
								//pThis->m_CriticalSectionLog.Lock();
								//失败，SN码一一写回
								//失败，从KEYPSD文件夹MOVEBACK
								//char path_buffer[_MAX_PATH];
								TCHAR drive[_MAX_DRIVE];
								TCHAR dir[_MAX_DIR];
								TCHAR fname[_MAX_FNAME];
								TCHAR ext[_MAX_EXT];
								_wsplitpath(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], drive, dir, fname, ext);
								if (pThis->stu_GenSetting.nIsDelete)
								{
									strtmp = g_wszCurPath;
								}
								else
								{
									strtmp = drive;
									strtmp += dir;
								}
								strtmp += L"KPsd\\";
								strtmp += fname;
								strtmp += ext;
								if (0 != (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i)))
								{

								}
								else
								{
									DeleteFile(strtmp);
									if (0 == MoveFile(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], strtmp))
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										strtmp += L" move fail";
										pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

									}
									else
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										if (wcslen(fname))
										{

											strtmp += L" moved";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
											if (pThis->stu_GenSetting.nIsDelete)
											{
												strtmp = g_wszCurPath;
											}
											else
											{
												strtmp = drive;
												strtmp += dir;
											}

											strtmp += L"KPsd\\";
											
											pThis->logPsdKey2(strtmp, fname);
											
										}
									}



								}
								idx++;
								//pThis->m_CriticalSectionLog.Unlock();
							}
						}
						pThis->m_CriticalSectionLog.Unlock();
					}

				}
			}
			
			if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				//全错 FAIL


				pThis->Beep(nThIdx, 2);


			}
			//成功，无错
			else if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->Beep(nThIdx, 0);
			}
			//计算时间
			if (cStatus != PROC_SOCKETALLERR)
			{
				pThis->m_TimeEnd[nThIdx] = CTime::GetCurrentTime();
				Timedif = pThis->m_TimeEnd[nThIdx] - pThis->m_TimeBegin[nThIdx];
				delay = Timedif.GetTotalSeconds();
				strtmp.Format(L"Total %d seconds", delay);
			
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
				pThis->pFormView3->RichEditShow(nThIdx, L"", OPERATIONCOLOR, 0, 0);
			}

			//删除KEY的记录
			for (i = 0; i < 10; i++)
			{
				pThis->stu_UserSNProg[nThIdx][i].nSnNum = 0;
				memset(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile, 0, sizeof(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile));
			}
			pThis->HighZ_CloseV(nThIdx);
		}
	}
	if (pThis->m_nIsAuto[nThIdx] == 0)
	{
		//串口 和网络
		if ((stu_RemoteStat.nRemoteStat > 0) && ((TRUE == stu_RemoteStat.isComOpened) || (pThis->m_SocketObject.IsOpen())))
		{

			

			for (i = 0; i < nSocketMax; i++)
			{
				//使能的SOCKET都RUN
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{
					//失败的
					if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i))
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
					//成功的
					else
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_OK;
					}

				}

				//未使能的，如果是SOCKET ERR=1，是座子号不对
				else
				{
				//	if (pThis->stu_UsbDeviceArr[nThIdx].cSokEncRet[i])
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
				}

			}
			g_SerialResBuf[(pThis->m_nSiteNo[nThIdx] - 1)] = SER_PROG_READY;


		}
		pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus = 0;
	}



	pThis->pFormView1->CntDisplayEachLeftListCtrl(nThIdx, 0);
	pThis->pFormView2->CntDisplayEachPanel(nThIdx);


	//压力测试
	//如果选择PINCHECK AUTO，使用压力测试的流程，把次数固定
	if (pThis->nAutoSenseAutoRun)
	{
		if (pThis->nAutoSenseAutoRunStartEnd % 2)
		{
			pThis->m_nAutoCntPressure[nThIdx] = 5;
		}
		else
		{
			pThis->m_nAutoCntPressure[nThIdx] = 0;
			pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
			pThis->nAutoSenseAutoRunStartEnd = 0;
			pThis->m_pThreadUsbData[nThIdx] = NULL;

		}

	}
	if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
	{
		if (pThis->m_nAutoCntPressure[nThIdx] > 0)
		{
			nSocketMax = 0;
			pThis->m_nAutoCntPressure[nThIdx]--;
			if (pThis->m_nAutoCntPressure[nThIdx] > 0)
			{
				pThis->m_nIsAuto[nThIdx] = 0xff;
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx = 0;

				goto PRESSURElOOP;
			}
		}
	}
	return 0;
}

UCHAR gSendbuf3[16 * 1024 * 1024];
UCHAR gReadbuf3[4 * 1024 * 1024];

//四个MAP不同之处
//pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread0, (LPVOID)pThis);
//AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap0, (LPVOID)pThis);
//PRESSURElOOP
//PCEND
//PCCANCEL
//USBERR
DWORD WINAPIV CMainFrame::UsbDataProcFileMap3(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR *pSendbuf = gSendbuf3;
	UCHAR *pReadbuf = gReadbuf3;
	CProgressCtrl *pCProgress = &pThis->pFormView2->m_progress3;
	UINT nSnOfset;

	
	CTimeSpan Timedif;
	int delay;
	CTime TimeBegin = CTime::GetCurrentTime();
	CTime TimeEnd;
	int len;
	int nThIdx = 3;
	int nBufDfLen;
	TCHAR wszPath[MAX_PATH];
	int nNeedDelKey = 0;
	TCHAR wsztemp[180];

	BYTE inEpAddress = 0x83, outEpAddress = 0x01;
	UCHAR cStatus = PROC_END;
	int base = 0;
	UINT *pInt;
	bool ret = 0;
	CString strtmp, showstr = L"";
	PUCHAR		buffersInput = pReadbuf;
	CCyUSBEndPoint *epBulkOut = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(outEpAddress);
	CCyUSBEndPoint *epBulkIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(0X81);
	CCyUSBEndPoint *epBulkCmdIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(inEpAddress);
	long writelenth = 0;
	long nWarnLed = 0;
	long nScale = 0;
	UCHAR *pcData;
	UINT checksum = 0;
	long readLenth = 1024 * 1024;
	UINT nCheckSums[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	UINT nBufferIdxRd[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	short wColoridx;
	int wErrMaskinoneproc = 0;
	int nNoticeBlue = 0;
	int nNoticePurple = 0;
	UINT64 llSeekAddr = 0;
	//最高位是1表示是读的BUF.
	UCHAR cBufIdx = 0;
	UCHAR  crCurBufIdx = 0;
	UCHAR  cwCurBufIdx = 0;
	UINT nSeekL = 0;
	USHORT wBufIdx8_Haddr8 = 0;
	if (epBulkOut == NULL || epBulkCmdIn == NULL || epBulkIn == NULL) return 1;
	int i, idx = 0;
	int nSocketSenseMask = 0;
	INT nSocketMax = SOCKETMAX;
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		nSocketMax = 2 * SOCKETMAX;
	
	for (i = 0; i < nSocketMax; i++)
	{
		//使能的SOCKET都RUN
		if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_RUN;
		}
		else
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_DISABLE;
		}

	}



	g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = SER_PROG_RUNNING;

	int nBtnIdx;
	Sleep(THDLY);
	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_RUN;


	if (0 == pThis->nAutoSenseAutoRun)
	{
		//没选autosense
	//单步或者AUTO 第一步,才需要下载算法。FPGA等。AUTO的后面几步就不需要了//叠料//非空擦除第一次擦除
		if ((pThis->m_nIsAuto[nThIdx] == 0) || ((pThis->m_nIsAuto[nThIdx]) && (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0)) || pThis->stu_overlap.nIsOverLapCheck[nThIdx] ||
			(g_nEraseWhenNOTBlank && ('e' == pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]])))
		{
			ret = pThis->DownloadConfig_GetPincheck(nThIdx);
		}
	}

	else
	{
		//选了AUTOsense，第一次要DownloadConfig_GetPincheck0，之后每个AUTO的第一次只要要SendConfiWord就行
		if ((pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0) || (0 == pThis->nAutoLoopFirst[nThIdx]))
		{
			pThis->pFormView3->RichEditShow(nThIdx, L"Please insert new chips.....", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 20);
			while (1)
			{

				if (0 == pThis->nAutoLoopFirst[nThIdx])
				{
					ret = pThis->DownloadConfig_GetPincheck(nThIdx);
					if (ret)break;

				}
				else
				{
					ret = pThis->SendConfiWord(nThIdx, 3, pThis->m_cDownData[nThIdx], sizeof(pThis->m_cDownData[nThIdx]));
					if (ret)break;
				}
				pThis->PinSenseInAuto(nThIdx, pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
				pThis->pFormView2->SenseBlink(nThIdx);
				for (i = 0; i < SOCKETMAX; i++)
				{
					if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit & (1 << i))
					{
						//第一次接触上就行
						if (pThis->nAutoLoopFirst[nThIdx])
						{
							if (BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}
						else
						{
							//之后要有状态便话，有先取再放的过程
							if ((BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]) || (BLINK_NULL == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]))
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}

					}
				}
				pThis->nAutoLoopFirst[nThIdx] = 1;
				if (nSocketSenseMask == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)break;
				//停止
				if (0 == (pThis->nAutoSenseAutoRunStartEnd % 2))
				{

					memset(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx]));
					//	memset(stu_PinCheckBlink.nStartBlinkArr[i], 0, sizeof(stu_PinCheckBlink.nStartBlinkArr[i]));
					memset(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx]));
					pThis->m_nAutoCntPressure[nThIdx] = 0;
					pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
					pThis->m_pThreadUsbData[nThIdx] = NULL;
					pThis->nAutoSenseAutoRunStartEnd = 0;
					pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
					for (i = 0; i < SOCKETMAX; i++)
					{
						if (BLINK_START == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
						{
							pThis->pFormView2->mp_Static_ModArr[nThIdx][i]->SetIcon(pThis->pFormView2->stu_PinCheckBlink.HiconsavedIcon[nThIdx][i]);
						}
					}
					return 0;

				}
			}
		}
	}
	if (ret)
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		return 0;
	}
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	strtmp += L" BEGIN...";
	pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 30);


	//OVERLAPPED		OutOvLap;
	//UCHAR *outContext;
	//延续上次的错误状态码
	wErrMaskinoneproc |= pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus;
	//传输数据是否512字节的倍数，要处理，否则，传输死机
	char cIs512Multy = 0;
	


	CString path;
	CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[0]);
	path.Format(L"%slib\\%s", g_wszCurPath, wsztemp);
	path += L".bf";
	//创建文件对象
	CFileException e;
	CFile64 wfile;
	CFile64 rfile;
	int nSnChnIdx = 0;
	CFile SnFile;



	//如果是读.开读的文件
	if (pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'r')
	{
		/*if (!wfile.Open(pThis->m_strReadFileDefaultPath[0], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

			return 0;
		}*/
	}
	strtmp = path;
	showstr = pThis->m_strReadFileDefaultPath[0];
	//if (strtmp.MakeUpper() != showstr.MakeUpper())
	{
		if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
			return 0;
		}
	}
	strtmp.Empty();
	showstr.Empty();


	//要注意的是,必须先操作完 pBuffer才能UnmapViewOfFile,
	//如果先UnmapViewOfFile,再操作 pBuffer则会出错,因为pBuffer已经被释放了
	pInt = (UINT*)pSendbuf;
	pcData = (UCHAR *)pSendbuf;

	epBulkOut->Abort();
	epBulkOut->Reset();
	epBulkCmdIn->Abort();
	epBulkCmdIn->Reset();
	epBulkIn->Abort();
	epBulkIn->Reset();

	//strtmp.Format(L"checksum=%u\n", checksum);
	pCProgress->SetRange(0, 100);
	epBulkOut->TimeOut = INFINITE;
	epBulkCmdIn->TimeOut = INFINITE;
	checksum = 0;


	//面板LED显示

	if (pThis->m_pThreadUserProc1[nThIdx] != NULL)
	{
		strtmp.Format(L"site%d thread proc ptr NOT NULL", pThis->m_nSiteNo[nThIdx]);
		AfxMessageBox(strtmp);
	}
	OVERLAPPED ovLapStatus;
	memset(&ovLapStatus, 0, sizeof(OVERLAPPED));
	ovLapStatus.hEvent = CreateEvent(NULL, false, false, NULL);
	int nMutex = 0;
	while (1)
	{
	
	
	 
	   

	    
		
		PUCHAR context = epBulkCmdIn->BeginDataXfer(buffersInput, readLenth, &ovLapStatus);
		if (nMutex == 0)
		{
			nMutex = 1;
			pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread, (LPVOID)&nThIdx);
		}
		
		bool   wResult = epBulkCmdIn->WaitForXfer(&ovLapStatus,INFINITE);
		bool   fResult = epBulkCmdIn->FinishDataXfer(buffersInput, readLenth, &ovLapStatus, context);

	    
		 ret =wResult && fResult;
		 if (ret != true)
		 {
			 CloseHandle(ovLapStatus.hEvent);
			 epBulkCmdIn->Abort();
			 epBulkOut->Abort();
			 //取消映射
			 if (rfile.IsOpen()) rfile.Close();
			 if (wfile.IsOpen()) wfile.Close();
			 pThis->pFormView3->RichEditShow(nThIdx, L"USB data req transfer err", COLOR_RED, 0, 0);
			 //关闭文件映射对象
			 pThis->m_pThreadUsbData[nThIdx] = NULL;
			 return -1;
		 }
		//OUT数据，主要流程，烧录校验
		if (buffersInput[0] == 'O')
		{
			cIs512Multy = buffersInput[1] & 4;
			memcpy(&writelenth, &buffersInput[2], 4);
			//0,1:SINGLE 和双BUFFER的STARTSTORE
			if ((buffersInput[1] & 3) <= 1)
			{
				if (cIs512Multy)
				{
					len=rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}

				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}

				//SN
				if ((cBufIdx & 0x7f) == BUFNUM)
				{
					pThis->m_CriticalSectionKey.Lock();

					//[0:3]第几组序列,低4位，,其余是OFFSET
					//[4]删除KEY文件吗
					//[5:31]OFFSET
					nSnChnIdx = llSeekAddr & 0xf;
					nNeedDelKey = ((llSeekAddr >> 4) & 1);
					nSnOfset = llSeekAddr >> 5;
					//取得几个序列号
					if (pThis->stu_GenSetting.nUserSnLen[nSnChnIdx])
					{
						int nSnCnt = writelenth / pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						writelenth = nSnCnt*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						if (writelenth > SIZE16MB - 1)
						{
							writelenth = SIZE2MB - 1;
							pThis->pFormView3->RichEditShow(nThIdx, L"change to 2MB(Key must <2MB)", COLOR_RED, 0, 0);
						}
						pThis->GetOneUserSn(nThIdx, nSnChnIdx, nSnOfset, nNeedDelKey, nSnCnt);
						pcData[0] = pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum;
						memcpy(pcData + 1, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr, writelenth);
						writelenth += 1;
					}
					else
					{
						writelenth = 2;
						memset(pcData, 0, writelenth);
					}

					pThis->m_CriticalSectionKey.Unlock();
				}
				//等待三秒

				epBulkOut->XferData(pcData, writelenth);



			}

#if 1

			//下一次准备
			//memset(pcData, 1, 1024);
			//双buffer

			if ((buffersInput[1] & 2))
			{
				if (cIs512Multy)
				{
					len=rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}



				epBulkOut->XferData(pcData, writelenth);


			}
			//
#endif

		}
		//IN数据，读
		else if (buffersInput[0] == 'I')
		{
			if (wfile.IsClosed())
			{
				if (!wfile.Open(pThis->m_strReadFileDefaultPath[cwCurBufIdx], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
				{
					strtmp.Format(L"Failed to open the file %s\n", e.m_strFileName);
					AfxMessageBox(strtmp);
					epBulkCmdIn->Abort();
					epBulkOut->Abort();

					pThis->m_pThreadUsbData[nThIdx] = NULL;
					return 0;
				}
			}
			if (g_nIsEmmc){pThis->m_nIsLoadBufferDll = 1;pThis->m_nIsReadFitnessNeedDataAnalysis=1;}
			cBufIdx |= 0x80;
			len = wfile.GetPosition();
			//把读之前SEEK的位置加上去
			if (llSeekAddr > len)
			{
				//如果要填充1
				if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cwCurBufIdx & 0x7f], "0"))
				{
					memset(pSendbuf, 0xff, SIZE16MB);
					len = llSeekAddr - len;
					for (i = 0; i < len / SIZE16MB; i++)
					{
						wfile.Write(pSendbuf, SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
					}

					if (len%SIZE16MB)
					{
						wfile.Write(pSendbuf, len%SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
					}

				}
				else
				{
					//直接填0
					wfile.Seek(llSeekAddr, CFile64::begin, 1);
				}


			}

			memcpy(&readLenth, &buffersInput[2], 4);
			ret = epBulkIn->XferData(buffersInput, readLenth);
			if (ret != true)
			{
				CloseHandle(ovLapStatus.hEvent);
				epBulkCmdIn->Abort();
				epBulkOut->Abort();
				epBulkIn->Abort();
				//取消映射
				if (rfile.IsOpen()) rfile.Close();
				if (wfile.IsOpen()) wfile.Close();
				pThis->pFormView3->RichEditShow(nThIdx, L"USB data in transfer err", COLOR_RED, 0, 0);
				//关闭文件映射对象
				pThis->m_pThreadUsbData[nThIdx] = NULL;
				return -1;
			}
			wfile.Write(buffersInput, readLenth);
			nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(buffersInput, readLenth);
			nBufferIdxRd[cwCurBufIdx] = 1;
			len = wfile.GetPosition();
		}
		//正常结束和CANCEL
		else if (buffersInput[0] == 'C')
		{
			if (0 == buffersInput[2])
			{
				//正常退出

				if (0 == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
				{
					//socket号都不对
					pThis->m_nIsAuto[nThIdx] = 0;
					cStatus = PROC_SOCKETALLERR;
				}
				//读追加文件末尾填充
				if (cBufIdx & 0x80)
				{
					if (wfile.IsOpen())
					{
						len = wfile.GetPosition();
						sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f], "%x", &nBufDfLen);
						//要追加填充
						if (nBufDfLen > len)
						{
							//如果要填充1
							if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cBufIdx & 0x7f], "0"))
							{
								len = nBufDfLen - len;
								memset(pSendbuf, 0xff, SIZE16MB);
								for (i = 0; i < len / SIZE16MB; i++)
								{
									wfile.Write(pSendbuf, SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
								}

								if (len%SIZE16MB)
								{
									wfile.Write(pSendbuf, len%SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
								}

							}
							else
							{
								//直接填0
								wfile.Seek(nBufDfLen, CFile64::begin, 1);
							}

						}
					}
					
				}

				//if (cBufIdx & 0x80)
				{
					for (i = 0; i < BUFNUM; i++)
					{
						if (nBufferIdxRd[i])
						{
							CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);

							strtmp.Format(L"%s Checksum=0x%08x", wsztemp, nCheckSums[i]);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
							if (g_nIsEmmc)pThis->pFormView2->DispChecksumInListCtrl(pThis->m_cComboBufSelMap[i], nCheckSums[i], nCheckSums[i]);
						}
					}

				}


				goto PCEND;
			}
			//
			else if (1 == buffersInput[2])
			{
				//cancel
				//	strtmp.Format(L"Cancel thread %s\n", __FUNCTIONW__);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 0, pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit);
				pCProgress->SetPos(0);
				//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				cStatus = PROC_CANCEL;
				pThis->m_nIsAuto[nThIdx] = 0;
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				//pThis->Beep(nThIdx, 0);
				goto PCCANCEL;

			}
			//算法FAIL上报
			else if (2 == buffersInput[2])
			{
				//cancel
				strtmp.Format(L"Fail\n");
				pCProgress->SetPos(0);
				if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				cStatus = PROC_END;
				//pThis->m_nIsAuto[nThIdx] = 0;
				goto PCEND;

			}

		}
		//DEBUGSTRING
		else if (buffersInput[0] == 'D')
		{
			if (0xff == ((UCHAR)buffersInput[2]))
			{
				int nColor = (buffersInput[3] << 16) | (buffersInput[4] << 8) | (buffersInput[5]);
				CharToTchar(wsztemp, (const char*)(buffersInput + 2 + 4));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, nColor, 0, 0);
			}
			else
			{
				CharToTchar(wsztemp, (const char*)(buffersInput + 2));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
			}


		}
		//进度条 PROGRESS
		else if (buffersInput[0] == 'P')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			pCProgress->SetPos(nScale);
			g_SerialResBuf[SERSOCKBASE + nSocketMax* 32 + (pThis->m_nSiteNo[nThIdx] - 1)] = nScale;

		}
		else if (buffersInput[0] == 'X')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			memcpy(g_ConfigData.nData, &buffersInput[2], 498);

		}
		//BufferSeek
		else if (buffersInput[0] == 'S')
		{

			memcpy(&nSeekL, &buffersInput[2], 4);
			memcpy(&wBufIdx8_Haddr8, &buffersInput[2 + 4], 2);
			llSeekAddr = (UINT64)(wBufIdx8_Haddr8 &0XFF)<< 32| nSeekL;
			cBufIdx = wBufIdx8_Haddr8 >> 8;

			//获得SN
			if ((cBufIdx & 0x7f) == BUFNUM)
			{

			}
			//写操作的BUFFER NUM与大于MAX
			else if (((cBufIdx & 0x7f) > BUFNUM) && ((cBufIdx & 0x80) == 0))
			{
				strtmp.Format(L"Buffer Idx>%d error\n", BUFNUM);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				pThis->Beep(nThIdx, 2);
				goto PCCANCEL;
			}

			//写操作时DEVICE没有这个BUFFER NUMBER
			else if (((cBufIdx & 0x80) == 0) && ((0 == strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[cBufIdx & 0x7f])) || (0 == strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f]))))
			{
				strtmp.Format(L"Buffer Idx %d Invalid\n", cBufIdx);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				goto PCCANCEL;
			}
			else if ((0 == (cBufIdx & 0x80)) && ((cBufIdx & 0X7F) == crCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是写操作

				rfile.Seek(llSeekAddr, CFile64::begin, 1);

			}
			else if ((cBufIdx & 0x80) && ((cBufIdx & 0X7F) == cwCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是读，啥也不干
			}
			//不同要重新打开文件
			else
			{
				//	if (Curfile.IsOpen())
				{
					//无论是否打开，当前读BUFFER idx都要更新
					cwCurBufIdx = cBufIdx & 0X7F;
					//读操作
					if (cBufIdx & 0x80)
					{
						if (wfile.IsOpen())
						{
							wfile.Close();
							strtmp.Format(L"wBuf%d closed", cwCurBufIdx);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
							
							//读直接用路径，不是BUFX
							path = pThis->m_strReadFileDefaultPath[cBufIdx & 0x7f];
							if (rfile.IsOpen())
							{
								if (rfile.GetFileName() == pThis->m_strReadFileDefaultPath[cwCurBufIdx])
								{
									rfile.Close();
								}
							}
							if (!wfile.Open(path, GENERIC_WRITE, 0, OPEN_ALWAYS, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								return 0;
							}
							strtmp.Format(L"buf%d open,seek %d\n", cwCurBufIdx, llSeekAddr);
						}

					}
					//写操作
					else
					{
						if (rfile.IsOpen())
						{
							rfile.Close();
							//strtmp.Format(L"wBuf%d closed", crCurBufIdx);
							//pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
						}
							crCurBufIdx = cBufIdx & 0X7F;
							CharToTchar(wszPath, pstuDevInfo[g_curDeviceSel].szBufNameArrs[crCurBufIdx]);
							path.Format(L"%slib\\%s", g_wszCurPath, wszPath);
							path += L".bf";
							if (wfile.IsOpen())
							{
								if (wfile.GetFileName() == path)
								{
									wfile.Close();
								}
							}
							if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								return 0;
							}
							rfile.Seek(llSeekAddr, CFile64::begin, 1);
							strtmp.Format(L"buf%d open,seek %d\n", crCurBufIdx, llSeekAddr);
						
					}


					//读的话，需要在读到数据的时候填充，不要直接SEEK，

				//	if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);

				}
			}

		}
		//LED状态显示颜色
		else if (buffersInput[0] == 'W')
		{
			memcpy(&nWarnLed, &buffersInput[2], 4);
			//pCProgress->SetPos(nScale);
			wColoridx = nWarnLed >> 16;
			//低16位是掩码

			if (WARNCOLOR_RED == wColoridx)
			{
				//有错误才显示红灯
				for (i = 0; i < nSocketMax; i++)
				{
					if (nWarnLed&(1 << i))
					{
						//重复SOCKET只显示一次
						if (0 == (wErrMaskinoneproc&(1 << i)))
						{
							if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
							{

								strtmp.Format(L"socket%d Failure", i + 1);
								if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 2);
							}

						}

					}
				}
				wErrMaskinoneproc |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_BLUE == wColoridx)
			{
				nNoticeBlue |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticeBlue&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_PURPLE == wColoridx)
			{
				nNoticePurple |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticePurple&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}

			else
			{
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nWarnLed&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}


		}

		if (ret != true)
		{
			pThis->stu_UsbDeviceArr[nThIdx].status = USBNOTCONNECT;

			//SOCKET设置未连接
			g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = USBNOTCONNECT;
			memset(&g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax], SER_SOCKET_DISABLE, nSocketMax);
			memset(&pThis->stu_AutoSeq[nThIdx], 0, sizeof(pThis->stu_AutoSeq[nThIdx]));
			cStatus = PROC_ERRSTOP;
			goto USBERR;

		}

	}

PCEND:
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	//如果选了叠料
	if (pThis->stu_overlap.nIsOverLapCheck[nThIdx])
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Checking", COLOR_YELLOW, 0, 0);
		wErrMaskinoneproc = (~(wErrMaskinoneproc))&(pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
		pThis->stu_overlap.nOverLapSockFail[nThIdx] = wErrMaskinoneproc;

		pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, pThis->stu_overlap.nOverLapSockFail[nThIdx]);
		//如果校验成功，代表叠料了

		if(pThis->stu_overlap.nOverLapSockFail[nThIdx])
		{
			if (pThis->stu_overlap.nOverLapSockFail[nThIdx] == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Check Fail", COLOR_RED, 0, 0);
				
			}
			for (i = 0; i < SOCKETMAX; i++)
			{
				if((1<<i)&(pThis->stu_overlap.nOverLapSockFail[nThIdx] ))
				{
					strtmp.Format(L"Sok %d overlap Fail", i + 1);
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				}
			}
			
		}
		
	}
		
	//如果选了空检查出错擦除，第一步是空检查，都OK的情况下，直接跳过下面的ERASE
	else if((pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'b')&&(g_nEraseWhenNOTBlank))
	{
		if(wErrMaskinoneproc==0)
		{
			pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;						
		}
		//g_nEraseWhenNOTBlank==1在BLANK中ERRMASK不能设置1，否则会导致后面退出
		wErrMaskinoneproc = 0;

	}
	
	//全错，又不是blank且g_nEraseWhenNOTBlank=0，则停止
	if (wErrMaskinoneproc == pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)
	{
		pThis->m_nIsAuto[nThIdx] = 0;
	}
PCCANCEL:
	pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus |= (wErrMaskinoneproc|pThis->stu_overlap.nOverLapSockFail[nThIdx]);

	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
USBERR:
	CloseHandle(ovLapStatus.hEvent);
	epBulkCmdIn->Abort();
	epBulkOut->Abort();
	//CloseHandle(OutOvLap.hEvent);
	//取消映射
	if (rfile.IsOpen())
		rfile.Close();
	if (wfile.IsOpen())
	{
		wfile.Close();
	}
	

	//关闭文件映射对象

	pThis->m_pThreadUsbData[nThIdx] = NULL;
	
	if (cStatus == PROC_CANCEL)
	{
		strtmp.Empty();
	}
	//如果SOCKET全部报错。就不报下面这些FINISHED了
	if (cStatus != PROC_SOCKETALLERR)
	{
		if (cStatus == PROC_CANCEL)strtmp += L" Canceled";
		else
		{
			if (0 == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" SUCCESS";;
			}
			else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" FAIL";
			}
			else
				strtmp += L" FINISHED";
		}
		if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 6);
		TimeEnd = CTime::GetCurrentTime();
		Timedif = TimeEnd - TimeBegin;
		delay = Timedif.GetMinutes() * 60 + Timedif.GetSeconds();
		strtmp.Format(L"%d seconds", delay);
		pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
	}

	if ((cStatus == PROC_END) || (cStatus == PROC_CANCEL))
	{
		//AUTO中
		if (pThis->m_nIsAuto[nThIdx])
		{
			//叠料检测那次不++；
			if (pThis->stu_overlap.nIsOverLapCheck[nThIdx] == 0)
			{
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;
				
			}
			else pThis->stu_overlap.nIsOverLapCheck[nThIdx] = 0;


		PRESSURElOOP:


			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx < pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				//中途掉线就不AUTO哦了
				if (pThis->stu_UsbDeviceArr[nThIdx].status != USBNOTCONNECT)
					AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap3, (LPVOID)pThis);
			}
			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
			}
		}
		//单次或者AUTO最后一次
		if (pThis->m_nIsAuto[nThIdx] == 0)
		{
			//记录本次失败的SOCKET
			pThis->m_FailSktLastAuto[nThIdx] = wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
			if (pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;

				if (0xff == (pThis->m_nBtnIdx & 0xff))
				{//确保是AUTO
					if (0 == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO SUCCESS";
					}
					else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO FAIL";
					}
					else
						strtmp = L"AUTO FINISHED";
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
				}
			}
			//统计
			for (i = 0; i < nSocketMax; i++)
			{
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{

					if ((wErrMaskinoneproc|pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus)&(1 << i))
					{

						pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[i]++;
						pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt++;
					}
					pThis->stu_UsbDeviceArr[nThIdx].nSokTotalCnt[i]++;
					pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt++;
				}
			}
			strtmp.Format(L"Total:%d  Success:%d  Fail:%d", pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt - pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 40);
			strtmp.Format(L"SockFail %d,%d,%d,%d,%d,%d,%d,%d", pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[0], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[1], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[2], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[3], \
				pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[4], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[5], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[6], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[7]);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 0);
			pThis->SummaryLog(nThIdx);
			//根据nSockProgStatus ,失败的写回SN 文件
			//if (nNeedDelKey)
			{
				for (nSnChnIdx = 0; nSnChnIdx < pThis->stu_GenSetting.nCnt; nSnChnIdx++)
				{
					if (pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum > 0)
					{
						idx = 0;
						pThis->m_CriticalSectionLog.Lock();
						for (i = 0; i < SOCKETMAX; i++)
						{
							//SOCKET不为空
							if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit&(1 << i))
							{
								//失败，SN码一一写回
								//失败，从KEYPSD文件夹MOVEBACK
								//char path_buffer[_MAX_PATH];
								TCHAR drive[_MAX_DRIVE];
								TCHAR dir[_MAX_DIR];
								TCHAR fname[_MAX_FNAME];
								TCHAR ext[_MAX_EXT];
								_wsplitpath(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], drive, dir, fname, ext);
								if (pThis->stu_GenSetting.nIsDelete)
								{
									strtmp = g_wszCurPath;
								}
								else
								{
									strtmp = drive;
									strtmp += dir;
								}
								strtmp += L"KPsd\\";
								strtmp += fname;
								strtmp += ext;
								if (0 != (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i)))
								{
#if 0
									if (0 != wcslen(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx]))
									{
										
										
										if (0 == MoveFile(strtmp, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx]))
										{
											strtmp.Format(L"Skt%d,", i + 1);
											strtmp += fname;
											strtmp += L" move back fail";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

										}
										else
										{
											strtmp.Format(L"Skt%d,", i + 1);
											strtmp += fname;
											strtmp += L" move backed";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
										}
										//SnFile.Open(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], CFile::modeCreate | CFile::modeWrite);
										//SnFile.Write(&pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr[idx*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx]], pThis->stu_GenSetting.nUserSnLen[nSnChnIdx]);
										//SnFile.Close();

									}

									else
									{
										/*AfxMessageBox(L"SN Number empty");
										pThis->m_CriticalSectionSnRd.Unlock();
										break;*/
									}
#endif
								}
								else
								{

									DeleteFile(strtmp);
									if (0 == MoveFile(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], strtmp))
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										strtmp += L" move fail";
										pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

									}
									else
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										if (wcslen(fname))
										{

											strtmp += L" moved";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
											if (pThis->stu_GenSetting.nIsDelete)
											{
												strtmp = g_wszCurPath;
											}
											else
											{
												strtmp = drive;
												strtmp += dir;
											}

											strtmp += L"KPsd\\";
											
											pThis->logPsdKey3(strtmp, fname);
											
										}
									}




								}
								idx++;

							}
						}
						pThis->m_CriticalSectionLog.Unlock();
					}

				}
			}
			
			if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				//全错 FAIL


				pThis->Beep(nThIdx, 2);


			}
			//成功，无错
			else if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->Beep(nThIdx, 0);
			}
			//计算时间
			if (cStatus != PROC_SOCKETALLERR)
			{
				pThis->m_TimeEnd[nThIdx] = CTime::GetCurrentTime();
				Timedif = pThis->m_TimeEnd[nThIdx] - pThis->m_TimeBegin[nThIdx];
				delay = Timedif.GetTotalSeconds();
				strtmp.Format(L"Total %d seconds", delay);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
				pThis->pFormView3->RichEditShow(nThIdx, L"", OPERATIONCOLOR, 0, 0);
			}

			//删除KEY的记录
			for (i = 0; i < 10; i++)
			{
				pThis->stu_UserSNProg[nThIdx][i].nSnNum = 0;
				memset(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile, 0, sizeof(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile));
			}
			pThis->HighZ_CloseV(nThIdx);
		}
	}
	if (pThis->m_nIsAuto[nThIdx] == 0)
	{
		//串口 和网络
		if ((stu_RemoteStat.nRemoteStat > 0) && ((TRUE == stu_RemoteStat.isComOpened) || (pThis->m_SocketObject.IsOpen())))
		{

			

			for (i = 0; i < nSocketMax; i++)
			{
				//使能的SOCKET都RUN
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{
					//失败的
					if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i))
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
					//成功的
					else
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_OK;
					}

				}

				//未使能的，如果是SOCKET ERR=1，是座子号不对
				else
				{
					//if (pThis->stu_UsbDeviceArr[nThIdx].cSokEncRet[i])
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
				}

			}
			g_SerialResBuf[(pThis->m_nSiteNo[nThIdx] - 1)] = SER_PROG_READY;


		}
		pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus = 0;
	}



	pThis->pFormView1->CntDisplayEachLeftListCtrl(nThIdx, 0);
	pThis->pFormView2->CntDisplayEachPanel(nThIdx);


	//压力测试
	//如果选择PINCHECK AUTO，使用压力测试的流程，把次数固定
	if (pThis->nAutoSenseAutoRun)
	{
		if (pThis->nAutoSenseAutoRunStartEnd % 2)
		{
			pThis->m_nAutoCntPressure[nThIdx] = 5;
		}
		else
		{
			pThis->m_nAutoCntPressure[nThIdx] = 0;
			pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
			pThis->nAutoSenseAutoRunStartEnd = 0;
			pThis->m_pThreadUsbData[nThIdx] = NULL;

		}

	}
	if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
	{
		if (pThis->m_nAutoCntPressure[nThIdx] > 0)
		{
			nSocketMax = 0;
			pThis->m_nAutoCntPressure[nThIdx]--;
			if (pThis->m_nAutoCntPressure[nThIdx] > 0)
			{
				pThis->m_nIsAuto[nThIdx] = 0xff;
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx = 0;

				goto PRESSURElOOP;
			}
		}
	}
	return 0;
}
UCHAR gSendbuf4[16 * 1024 * 1024];
UCHAR gReadbuf4[4 * 1024 * 1024];
//四个MAP不同之处
//pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread0, (LPVOID)pThis);
//AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap0, (LPVOID)pThis);
//PRESSURElOOP
//PCEND
//PCCANCEL
//USBERR
DWORD WINAPIV CMainFrame::UsbDataProcFileMap4(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR *pSendbuf = gSendbuf4;
	UCHAR *pReadbuf = gReadbuf4;
	CProgressCtrl *pCProgress = &pThis->pFormView2->m_progress4;
	UINT nSnOfset;

	CTimeSpan Timedif;
	int delay;
	CTime TimeBegin = CTime::GetCurrentTime();
	CTime TimeEnd;

	int len;
	int nThIdx = 4;
	int nBufDfLen;
	TCHAR wszPath[MAX_PATH];
	int nNeedDelKey = 0;
	TCHAR wsztemp[180];

	BYTE inEpAddress = 0x83, outEpAddress = 0x01;
	UCHAR cStatus = PROC_END;
	int base = 0;
	UINT *pInt;
	bool ret = 0;
	CString strtmp, showstr = L"";
	PUCHAR		buffersInput = pReadbuf;
	CCyUSBEndPoint *epBulkOut = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(outEpAddress);
	CCyUSBEndPoint *epBulkIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(0X81);
	CCyUSBEndPoint *epBulkCmdIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(inEpAddress);
	long writelenth = 0;
	long nWarnLed = 0;
	long nScale = 0;
	UCHAR *pcData;
	UINT checksum = 0;
	long readLenth = 1024 * 1024;
	UINT nCheckSums[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	UINT nBufferIdxRd[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	short wColoridx;
	int wErrMaskinoneproc = 0;
	int nNoticeBlue = 0;
	int nNoticePurple = 0;
	UINT64 llSeekAddr = 0;
	//最高位是1表示是读的BUF.
	UCHAR cBufIdx = 0;
	UCHAR  crCurBufIdx = 0;
	UCHAR  cwCurBufIdx = 0;
	UINT nSeekL = 0;
	USHORT wBufIdx8_Haddr8 = 0;
	if (epBulkOut == NULL || epBulkCmdIn == NULL || epBulkIn == NULL) return 1;
	int i, idx = 0;
	int nSocketSenseMask = 0;
	INT nSocketMax = SOCKETMAX;
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		nSocketMax = 2 * SOCKETMAX;
	
	for (i = 0; i < nSocketMax; i++)
	{
		//使能的SOCKET都RUN
		if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_RUN;
		}
		else
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_DISABLE;
		}

	}


	g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = SER_PROG_RUNNING;

	int nBtnIdx;
	Sleep(THDLY);
	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_RUN;


	if (0 == pThis->nAutoSenseAutoRun)
	{
		//没选autosense
	//单步或者AUTO 第一步,才需要下载算法。FPGA等。AUTO的后面几步就不需要了//叠料//非空擦除第一次擦除
		if ((pThis->m_nIsAuto[nThIdx] == 0) || ((pThis->m_nIsAuto[nThIdx]) && (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0)) || pThis->stu_overlap.nIsOverLapCheck[nThIdx] ||
			(g_nEraseWhenNOTBlank && ('e' == pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]])))
		{
			ret = pThis->DownloadConfig_GetPincheck(nThIdx);
		}
	}

	else
	{
		//选了AUTOsense，第一次要DownloadConfig_GetPincheck0，之后每个AUTO的第一次只要要SendConfiWord就行
		if ((pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0) || (0 == pThis->nAutoLoopFirst[nThIdx]))
		{
			pThis->pFormView3->RichEditShow(nThIdx, L"Please insert new chips.....", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 20);
			while (1)
			{

				if (0 == pThis->nAutoLoopFirst[nThIdx])
				{
					ret = pThis->DownloadConfig_GetPincheck(nThIdx);
					if (ret)break;

				}
				else
				{
					ret = pThis->SendConfiWord(nThIdx, 3, pThis->m_cDownData[nThIdx], sizeof(pThis->m_cDownData[nThIdx]));
					if (ret)break;
				}
				pThis->PinSenseInAuto(nThIdx, pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
				pThis->pFormView2->SenseBlink(nThIdx);
				for (i = 0; i < SOCKETMAX; i++)
				{
					if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit & (1 << i))
					{
						//第一次接触上就行
						if (pThis->nAutoLoopFirst[nThIdx])
						{
							if (BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}
						else
						{
							//之后要有状态便话，有先取再放的过程
							if ((BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]) || (BLINK_NULL == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]))
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}

					}
				}
				pThis->nAutoLoopFirst[nThIdx] = 1;
				if (nSocketSenseMask == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)break;
				//停止
				if (0 == (pThis->nAutoSenseAutoRunStartEnd % 2))
				{

					memset(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx]));
					//	memset(stu_PinCheckBlink.nStartBlinkArr[i], 0, sizeof(stu_PinCheckBlink.nStartBlinkArr[i]));
					memset(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx]));
					pThis->m_nAutoCntPressure[nThIdx] = 0;
					pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
					pThis->m_pThreadUsbData[nThIdx] = NULL;
					pThis->nAutoSenseAutoRunStartEnd = 0;
					pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
					for (i = 0; i < SOCKETMAX; i++)
					{
						if (BLINK_START == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
						{
							pThis->pFormView2->mp_Static_ModArr[nThIdx][i]->SetIcon(pThis->pFormView2->stu_PinCheckBlink.HiconsavedIcon[nThIdx][i]);
						}
					}
					return 0;

				}
			}
		}
	}
	if (ret)
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		return 0;
	}
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	strtmp += L" BEGIN...";
	pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 30);

	//OVERLAPPED		OutOvLap;
	//UCHAR *outContext;
	//延续上次的错误状态码
	wErrMaskinoneproc |= pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus;
	//传输数据是否512字节的倍数，要处理，否则，传输死机
	char cIs512Multy = 0;
	


	CString path;
	CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[0]);
	path.Format(L"%slib\\%s", g_wszCurPath, wsztemp);
	path += L".bf";
	//创建文件对象
	CFileException e;
	CFile64 wfile;
	CFile64 rfile;
	int nSnChnIdx = 0;
	CFile SnFile;



	//如果是读.开读的文件
	if (pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'r')
	{
		/*if (!wfile.Open(pThis->m_strReadFileDefaultPath[0], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

			return 0;
		}*/
	}
	strtmp = path;
	showstr = pThis->m_strReadFileDefaultPath[0];
	//if (strtmp.MakeUpper() != showstr.MakeUpper())
	{
		if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
			return 0;
		}
	}
	strtmp.Empty();
	showstr.Empty();


	//要注意的是,必须先操作完 pBuffer才能UnmapViewOfFile,
	//如果先UnmapViewOfFile,再操作 pBuffer则会出错,因为pBuffer已经被释放了
	pInt = (UINT*)pSendbuf;
	pcData = (UCHAR *)pSendbuf;

	epBulkOut->Abort();
	epBulkOut->Reset();
	epBulkCmdIn->Abort();
	epBulkCmdIn->Reset();
	epBulkIn->Abort();
	epBulkIn->Reset();

	//strtmp.Format(L"checksum=%u\n", checksum);
	pCProgress->SetRange(0, 100);
	epBulkOut->TimeOut = INFINITE;
	epBulkCmdIn->TimeOut = INFINITE;
	checksum = 0;


	//面板LED显示

	if (pThis->m_pThreadUserProc1[nThIdx] != NULL)
	{
		strtmp.Format(L"site%d thread proc ptr NOT NULL", pThis->m_nSiteNo[nThIdx]);
		AfxMessageBox(strtmp);
	}
	OVERLAPPED ovLapStatus;
	memset(&ovLapStatus, 0, sizeof(OVERLAPPED));
	ovLapStatus.hEvent = CreateEvent(NULL, false, false, NULL);
	int nMutex = 0;
	while (1)
	{
	
	
	 
	   

	    
		
		PUCHAR context = epBulkCmdIn->BeginDataXfer(buffersInput, readLenth, &ovLapStatus);
		if (nMutex == 0)
		{
			nMutex = 1;
			pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread, (LPVOID)&nThIdx);
		}
		
		bool   wResult = epBulkCmdIn->WaitForXfer(&ovLapStatus,INFINITE);
		bool   fResult = epBulkCmdIn->FinishDataXfer(buffersInput, readLenth, &ovLapStatus, context);

	    
		 ret =wResult && fResult;
		 if (ret != true)
		 {
			 CloseHandle(ovLapStatus.hEvent);
			 epBulkCmdIn->Abort();
			 epBulkOut->Abort();
			 //取消映射
			 if (rfile.IsOpen()) rfile.Close();
			 if (wfile.IsOpen()) wfile.Close();
			 pThis->pFormView3->RichEditShow(nThIdx, L"USB data req transfer err", COLOR_RED, 0, 0);
			 //关闭文件映射对象
			 pThis->m_pThreadUsbData[nThIdx] = NULL;
			 return -1;
		 }
		//OUT数据，主要流程，烧录校验
		if (buffersInput[0] == 'O')
		{
			cIs512Multy = buffersInput[1] & 4;
			memcpy(&writelenth, &buffersInput[2], 4);
			//0,1:SINGLE 和双BUFFER的STARTSTORE
			if ((buffersInput[1] & 3) <= 1)
			{
				if (cIs512Multy)
				{
					len=rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}

				//SN
				if ((cBufIdx & 0x7f) == BUFNUM)
				{
					pThis->m_CriticalSectionKey.Lock();

					//[0:3]第几组序列,低4位，,其余是OFFSET
					//[4]删除KEY文件吗
					//[5:31]OFFSET
					nSnChnIdx = llSeekAddr & 0xf;
					nNeedDelKey = ((llSeekAddr >> 4) & 1);
					nSnOfset = llSeekAddr >> 5;
					//取得几个序列号
					if (pThis->stu_GenSetting.nUserSnLen[nSnChnIdx])
					{
						int nSnCnt = writelenth / pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						writelenth = nSnCnt*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						if (writelenth > SIZE16MB - 1)
						{
							writelenth = SIZE2MB - 1;
							pThis->pFormView3->RichEditShow(nThIdx, L"change to 2MB(Key must <2MB)", COLOR_RED, 0, 0);
						}
						pThis->GetOneUserSn(nThIdx, nSnChnIdx, nSnOfset, nNeedDelKey, nSnCnt);
						pcData[0] = pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum;
						memcpy(pcData + 1, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr, writelenth);
						writelenth += 1;
					}
					else
					{
						writelenth = 2;
						memset(pcData, 0, writelenth);
					}

					pThis->m_CriticalSectionKey.Unlock();
				}
				//等待三秒

				epBulkOut->XferData(pcData, writelenth);



			}

#if 1

			//下一次准备
			//memset(pcData, 1, 1024);
			//双buffer

			if ((buffersInput[1] & 2))
			{
				if (cIs512Multy)
				{
					len=rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}



				epBulkOut->XferData(pcData, writelenth);


			}
			//
#endif

		}
		//IN数据，读
		else if (buffersInput[0] == 'I')
		{
			if (wfile.IsClosed())
			{
				if (!wfile.Open(pThis->m_strReadFileDefaultPath[cwCurBufIdx], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
				{
					strtmp.Format(L"Failed to open the file %s\n", e.m_strFileName);
					AfxMessageBox(strtmp);
					epBulkCmdIn->Abort();
					epBulkOut->Abort();

					pThis->m_pThreadUsbData[nThIdx] = NULL;
					return 0;
				}
			}
			if (g_nIsEmmc){pThis->m_nIsLoadBufferDll = 1;pThis->m_nIsReadFitnessNeedDataAnalysis=1;}
			cBufIdx |= 0x80;
			len = wfile.GetPosition();
			//把读之前SEEK的位置加上去
			if (llSeekAddr > len)
			{
				//如果要填充1
				if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cwCurBufIdx & 0x7f], "0"))
				{
					memset(pSendbuf, 0xff, SIZE16MB);
					len = llSeekAddr - len;
					for (i = 0; i < len / SIZE16MB; i++)
					{
						wfile.Write(pSendbuf, SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
					}

					if (len%SIZE16MB)
					{
						wfile.Write(pSendbuf, len%SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
					}

				}
				else
				{
					//直接填0
					wfile.Seek(llSeekAddr, CFile64::begin, 1);
				}


			}

			memcpy(&readLenth, &buffersInput[2], 4);
			ret = epBulkIn->XferData(buffersInput, readLenth);
			if (ret != true)
			{
				CloseHandle(ovLapStatus.hEvent);
				epBulkCmdIn->Abort();
				epBulkOut->Abort();
				epBulkIn->Abort();
				//取消映射
				if (rfile.IsOpen()) rfile.Close();
				if (wfile.IsOpen()) wfile.Close();
				pThis->pFormView3->RichEditShow(nThIdx, L"USB data in transfer err", COLOR_RED, 0, 0);
				//关闭文件映射对象
				pThis->m_pThreadUsbData[nThIdx] = NULL;
				return -1;
			}
			wfile.Write(buffersInput, readLenth);
			nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(buffersInput, readLenth);
			nBufferIdxRd[cwCurBufIdx] = 1;
			len = wfile.GetPosition();
		}
		//正常结束和CANCEL
		else if (buffersInput[0] == 'C')
		{
			if (0 == buffersInput[2])
			{
				//正常退出

				if (0 == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
				{
					//socket号都不对
					pThis->m_nIsAuto[nThIdx] = 0;
					cStatus = PROC_SOCKETALLERR;
				}
				//读追加文件末尾填充
				if (cBufIdx & 0x80)
				{
					if (wfile.IsOpen())
					{
						len = wfile.GetPosition();
						sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f], "%x", &nBufDfLen);
						//要追加填充
						if (nBufDfLen > len)
						{
							//如果要填充1
							if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cBufIdx & 0x7f], "0"))
							{
								len = nBufDfLen - len;
								memset(pSendbuf, 0xff, SIZE16MB);
								for (i = 0; i < len / SIZE16MB; i++)
								{
									wfile.Write(pSendbuf, SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
								}

								if (len%SIZE16MB)
								{
									wfile.Write(pSendbuf, len%SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
								}

							}
							else
							{
								//直接填0
								wfile.Seek(nBufDfLen, CFile64::begin, 1);
							}

						}
					}
					
				}

				//if (cBufIdx & 0x80)
				{
					for (i = 0; i < BUFNUM; i++)
					{
						if (nBufferIdxRd[i])
						{
							CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);

							strtmp.Format(L"%s Checksum=0x%08x", wsztemp, nCheckSums[i]);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
							if (g_nIsEmmc)pThis->pFormView2->DispChecksumInListCtrl(pThis->m_cComboBufSelMap[i], nCheckSums[i], nCheckSums[i]);
						}
					}

				}


				goto PCEND;
			}
			//
			else if (1 == buffersInput[2])
			{
				//cancel
				//	strtmp.Format(L"Cancel thread %s\n", __FUNCTIONW__);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 0, pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit);
				pCProgress->SetPos(0);
				//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				cStatus = PROC_CANCEL;
				pThis->m_nIsAuto[nThIdx] = 0;
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				//pThis->Beep(nThIdx, 0);;
				goto PCCANCEL;

			}
			//算法FAIL上报
			else if (2 == buffersInput[2])
			{
				//cancel
				strtmp.Format(L"Fail\n");
				pCProgress->SetPos(0);
				if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				cStatus = PROC_END;
			//	pThis->m_nIsAuto[nThIdx] = 0;
				goto PCEND;

			}

		}
		//DEBUGSTRING
		else if (buffersInput[0] == 'D')
		{
			if (0xff == ((UCHAR)buffersInput[2]))
			{
				int nColor = (buffersInput[3] << 16) | (buffersInput[4] << 8) | (buffersInput[5]);
				CharToTchar(wsztemp, (const char*)(buffersInput + 2 + 4));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, nColor, 0, 0);
			}
			else
			{
				CharToTchar(wsztemp, (const char*)(buffersInput + 2));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
			}


		}
		//进度条 PROGRESS
		else if (buffersInput[0] == 'P')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			pCProgress->SetPos(nScale);
			g_SerialResBuf[SERSOCKBASE + nSocketMax* 32 + (pThis->m_nSiteNo[nThIdx] - 1)] = nScale;

		}
		else if (buffersInput[0] == 'X')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			memcpy(g_ConfigData.nData, &buffersInput[2], 498);

		}
		//BufferSeek
		else if (buffersInput[0] == 'S')
		{

			memcpy(&nSeekL, &buffersInput[2], 4);
			memcpy(&wBufIdx8_Haddr8, &buffersInput[2 + 4], 2);
			llSeekAddr = (UINT64)(wBufIdx8_Haddr8 &0XFF)<< 32| nSeekL;
			cBufIdx = wBufIdx8_Haddr8 >> 8;

			//获得SN
			if ((cBufIdx & 0x7f) == BUFNUM)
			{

			}
			//写操作的BUFFER NUM与大于MAX
			else if (((cBufIdx & 0x7f) > BUFNUM) && ((cBufIdx & 0x80) == 0))
			{
				strtmp.Format(L"Buffer Idx>%d error\n", BUFNUM);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				pThis->Beep(nThIdx, 2);
				goto PCCANCEL;
			}

			//写操作时DEVICE没有这个BUFFER NUMBER
			else if (((cBufIdx & 0x80) == 0) && ((0 == strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[cBufIdx & 0x7f])) || (0 == strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f]))))
			{
				strtmp.Format(L"Buffer Idx %d Invalid\n", cBufIdx);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				goto PCCANCEL;
			}
			else if ((0 == (cBufIdx & 0x80)) && ((cBufIdx & 0X7F) == crCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是写操作

				rfile.Seek(llSeekAddr, CFile64::begin, 1);

			}
			else if ((cBufIdx & 0x80) && ((cBufIdx & 0X7F) == cwCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是读，啥也不干
			}
			//不同要重新打开文件
			else
			{
				//	if (Curfile.IsOpen())
				{
					//无论是否打开，当前读BUFFER idx都要更新
					cwCurBufIdx = cBufIdx & 0X7F;
					//读操作
					if (cBufIdx & 0x80)
					{
						if (wfile.IsOpen())
						{
							wfile.Close();
							strtmp.Format(L"wBuf%d closed", cwCurBufIdx);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
							
							//读直接用路径，不是BUFX
							path = pThis->m_strReadFileDefaultPath[cBufIdx & 0x7f];
							if (rfile.IsOpen())
							{
								if (rfile.GetFileName() == pThis->m_strReadFileDefaultPath[cwCurBufIdx])
								{
									rfile.Close();
								}
							}
							if (!wfile.Open(path, GENERIC_WRITE, 0, OPEN_ALWAYS, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								return 0;
							}
							strtmp.Format(L"buf%d open,seek %d\n", cwCurBufIdx, llSeekAddr);
						}

					}
					//写操作
					else
					{
						if (rfile.IsOpen())
						{
							rfile.Close();
						//	strtmp.Format(L"wBuf%d closed", crCurBufIdx);
						//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
						}
							crCurBufIdx = cBufIdx & 0X7F;
							CharToTchar(wszPath, pstuDevInfo[g_curDeviceSel].szBufNameArrs[crCurBufIdx]);
							path.Format(L"%slib\\%s", g_wszCurPath, wszPath);
							path += L".bf";
							if (wfile.IsOpen())
							{
								if (wfile.GetFileName() == path)
								{
									wfile.Close();
								}
							}
							if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								return 0;
							}
							rfile.Seek(llSeekAddr, CFile64::begin, 1);
							strtmp.Format(L"buf%d open,seek %d\n", crCurBufIdx, llSeekAddr);
						
					}


					//读的话，需要在读到数据的时候填充，不要直接SEEK，

			//		if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);

				}
			}

		}
		//LED状态显示颜色
		else if (buffersInput[0] == 'W')
		{
			memcpy(&nWarnLed, &buffersInput[2], 4);
			//pCProgress->SetPos(nScale);
			wColoridx = nWarnLed >> 16;
			//低16位是掩码

			if (WARNCOLOR_RED == wColoridx)
			{
				//有错误才显示红灯
				for (i = 0; i < nSocketMax; i++)
				{
					if (nWarnLed&(1 << i))
					{
						//重复SOCKET只显示一次
						if (0 == (wErrMaskinoneproc&(1 << i)))
						{
							if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
							{

								strtmp.Format(L"socket%d Failure", i + 1);
								if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 2);
							}

						}

					}
				}
				wErrMaskinoneproc |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_BLUE == wColoridx)
			{
				nNoticeBlue |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticeBlue&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_PURPLE == wColoridx)
			{
				nNoticePurple |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticePurple&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}

			else
			{
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nWarnLed&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}


		}

		if (ret != true)
		{
			pThis->stu_UsbDeviceArr[nThIdx].status = USBNOTCONNECT;

			//SOCKET设置未连接
			g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = USBNOTCONNECT;
			memset(&g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax], SER_SOCKET_DISABLE, nSocketMax);
			memset(&pThis->stu_AutoSeq[nThIdx], 0, sizeof(pThis->stu_AutoSeq[nThIdx]));
			cStatus = PROC_ERRSTOP;
			goto USBERR;

		}

	}

PCEND:
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	//如果选了叠料
	if (pThis->stu_overlap.nIsOverLapCheck[nThIdx])
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Checking", COLOR_YELLOW, 0, 0);
		wErrMaskinoneproc = (~(wErrMaskinoneproc))&(pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
		pThis->stu_overlap.nOverLapSockFail[nThIdx] = wErrMaskinoneproc;

		pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, pThis->stu_overlap.nOverLapSockFail[nThIdx]);
		//如果校验成功，代表叠料了

		if(pThis->stu_overlap.nOverLapSockFail[nThIdx])
		{
			if (pThis->stu_overlap.nOverLapSockFail[nThIdx] == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Check Fail", COLOR_RED, 0, 0);
				
			}
			for (i = 0; i < SOCKETMAX; i++)
			{
				if((1<<i)&(pThis->stu_overlap.nOverLapSockFail[nThIdx] ))
				{
					strtmp.Format(L"Sok %d overlap Fail", i + 1);
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				}
			}
			
		}
		
	}
		
	//如果选了空检查出错擦除，第一步是空检查，都OK的情况下，直接跳过下面的ERASE
	else if((pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'b')&&(g_nEraseWhenNOTBlank))
	{
		if(wErrMaskinoneproc==0)
		{
			pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;						
		}
		//g_nEraseWhenNOTBlank==1在BLANK中ERRMASK不能设置1，否则会导致后面退出
		wErrMaskinoneproc = 0;

	}
	
	//全错，又不是blank且g_nEraseWhenNOTBlank=0，则停止
	if (wErrMaskinoneproc == pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)
	{
		pThis->m_nIsAuto[nThIdx] = 0;
	}
PCCANCEL:
	pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus |= (wErrMaskinoneproc|pThis->stu_overlap.nOverLapSockFail[nThIdx]);


	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
USBERR:
	CloseHandle(ovLapStatus.hEvent);
	epBulkCmdIn->Abort();
	epBulkOut->Abort();
	//CloseHandle(OutOvLap.hEvent);
	//取消映射
	if (rfile.IsOpen())
		rfile.Close();
	if (wfile.IsOpen())
	{
		wfile.Close();
	}


	//关闭文件映射对象

	pThis->m_pThreadUsbData[nThIdx] = NULL;

	if (cStatus == PROC_CANCEL)
	{
		strtmp.Empty();
	}
	//如果SOCKET全部报错。就不报下面这些FINISHED了
	if (cStatus != PROC_SOCKETALLERR)
	{
		if (cStatus == PROC_CANCEL)strtmp += L" Canceled";
		else
		{
			if (0 == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" SUCCESS";;
			}
			else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" FAIL";
			}
			else
				strtmp += L" FINISHED";
		}
		if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 6);
		TimeEnd = CTime::GetCurrentTime();
		Timedif = TimeEnd - TimeBegin;
		delay = Timedif.GetMinutes() * 60 + Timedif.GetSeconds();
		strtmp.Format(L"%d seconds", delay);
		pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
	}

	if ((cStatus == PROC_END) || (cStatus == PROC_CANCEL))
	{
		//AUTO中
		if (pThis->m_nIsAuto[nThIdx])
		{
			//叠料检测那次不++；
			if (pThis->stu_overlap.nIsOverLapCheck[nThIdx] == 0)
			{
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;
				
			}
			else pThis->stu_overlap.nIsOverLapCheck[nThIdx] = 0;


		PRESSURElOOP:


			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx < pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				//中途掉线就不AUTO哦了
				if (pThis->stu_UsbDeviceArr[nThIdx].status != USBNOTCONNECT)
					AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap4, (LPVOID)pThis);
			}
			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
			}
		}
		//单次或者AUTO最后一次
		if (pThis->m_nIsAuto[nThIdx] == 0)
		{
			//记录本次失败的SOCKET
			pThis->m_FailSktLastAuto[nThIdx] = wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
			if (pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;

				if (0xff == (pThis->m_nBtnIdx & 0xff))
				{//确保是AUTO
					if (0 == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO SUCCESS";
					}
					else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO FAIL";
					}
					else
						strtmp = L"AUTO FINISHED";
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
				}
			}
			//统计
			for (i = 0; i < nSocketMax; i++)
			{
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{

					if ((wErrMaskinoneproc|pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus)&(1 << i))
					{

						pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[i]++;
						pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt++;
					}
					pThis->stu_UsbDeviceArr[nThIdx].nSokTotalCnt[i]++;
					pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt++;
				}
			}
			strtmp.Format(L"Total:%d  Success:%d  Fail:%d", pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt - pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 40);
			strtmp.Format(L"SockFail %d,%d,%d,%d,%d,%d,%d,%d", pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[0], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[1], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[2], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[3], \
				pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[4], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[5], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[6], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[7]);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 0);
			pThis->SummaryLog(nThIdx);
			//根据nSockProgStatus ,失败的写回SN 文件
			//if (nNeedDelKey)
			{
				for (nSnChnIdx = 0; nSnChnIdx < pThis->stu_GenSetting.nCnt; nSnChnIdx++)
				{
					if (pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum > 0)
					{
						idx = 0;
						pThis->m_CriticalSectionLog.Lock();
						for (i = 0; i < SOCKETMAX; i++)
						{
							//SOCKET不为空
							if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit&(1 << i))
							{
								//失败，SN码一一写回
								//失败，从KEYPSD文件夹MOVEBACK
								//char path_buffer[_MAX_PATH];
								TCHAR drive[_MAX_DRIVE];
								TCHAR dir[_MAX_DIR];
								TCHAR fname[_MAX_FNAME];
								TCHAR ext[_MAX_EXT];
								_wsplitpath(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], drive, dir, fname, ext);
								if (pThis->stu_GenSetting.nIsDelete)
								{
									strtmp = g_wszCurPath;
								}
								else
								{
									strtmp = drive;
									strtmp += dir;
								}
								strtmp += L"KPsd\\";
								strtmp += fname;
								strtmp += ext;
								if (0 != (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i)))
								{
#if 0
									if (0 != wcslen(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx]))
									{


										if (0 == MoveFile(strtmp, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx]))
										{
											strtmp.Format(L"Skt%d,", i + 1);
											strtmp += fname;
											strtmp += L" move back fail";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

										}
										else
										{
											strtmp.Format(L"Skt%d,", i + 1);
											strtmp += fname;
											strtmp += L" move backed";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
										}
										//SnFile.Open(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], CFile::modeCreate | CFile::modeWrite);
										//SnFile.Write(&pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr[idx*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx]], pThis->stu_GenSetting.nUserSnLen[nSnChnIdx]);
										//SnFile.Close();

									}

									else
									{
										/*AfxMessageBox(L"SN Number empty");
										pThis->m_CriticalSectionSnRd.Unlock();
										break;*/
									}
#endif
								}
								else
								{

									DeleteFile(strtmp);
									if (0 == MoveFile(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], strtmp))
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										strtmp += L" move fail";
										pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

									}
									else
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										if (wcslen(fname))
										{

											strtmp += L" moved";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
											if (pThis->stu_GenSetting.nIsDelete)
											{
												strtmp = g_wszCurPath;
											}
											else
											{
												strtmp = drive;
												strtmp += dir;
											}

											strtmp += L"KPsd\\";

											pThis->logPsdKey4(strtmp, fname);

										}
									}

								}
								idx++;

							}
						}
						pThis->m_CriticalSectionLog.Unlock();
					}

				}
			}

			if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				//全错 FAIL


				pThis->Beep(nThIdx, 2);


			}
			//成功，无错
			else if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->Beep(nThIdx, 0);
			}
			//计算时间
			if (cStatus != PROC_SOCKETALLERR)
			{
				pThis->m_TimeEnd[nThIdx] = CTime::GetCurrentTime();
				Timedif = pThis->m_TimeEnd[nThIdx] - pThis->m_TimeBegin[nThIdx];
				delay = Timedif.GetTotalSeconds();
				strtmp.Format(L"Total %d seconds", delay);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
				pThis->pFormView3->RichEditShow(nThIdx, L"", OPERATIONCOLOR, 0, 0);
			}

			//删除KEY的记录
			for (i = 0; i < 10; i++)
			{
				pThis->stu_UserSNProg[nThIdx][i].nSnNum = 0;
				memset(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile, 0, sizeof(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile));
			}
			pThis->HighZ_CloseV(nThIdx);
		}
	}
	if (pThis->m_nIsAuto[nThIdx] == 0)
	{
		//串口 和网络
		if ((stu_RemoteStat.nRemoteStat > 0) && ((TRUE == stu_RemoteStat.isComOpened) || (pThis->m_SocketObject.IsOpen())))
		{

			

			for (i = 0; i < nSocketMax; i++)
			{
				//使能的SOCKET都RUN
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{
					//失败的
					if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i))
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
					//成功的
					else
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_OK;
					}

				}

				//未使能的，如果是SOCKET ERR=1，是座子号不对
				else
				{
					//if (pThis->stu_UsbDeviceArr[nThIdx].cSokEncRet[i])
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
				}

			}
			g_SerialResBuf[(pThis->m_nSiteNo[nThIdx] - 1)] = SER_PROG_READY;


		}
		pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus = 0;
	}



	pThis->pFormView1->CntDisplayEachLeftListCtrl(nThIdx, 0);
	pThis->pFormView2->CntDisplayEachPanel(nThIdx);


	//压力测试
	//如果选择PINCHECK AUTO，使用压力测试的流程，把次数固定
	if (pThis->nAutoSenseAutoRun)
	{
		if (pThis->nAutoSenseAutoRunStartEnd % 2)
		{
			pThis->m_nAutoCntPressure[nThIdx] = 5;
		}
		else
		{
			pThis->m_nAutoCntPressure[nThIdx] = 0;
			pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
			pThis->nAutoSenseAutoRunStartEnd = 0;
			pThis->m_pThreadUsbData[nThIdx] = NULL;

		}

	}
	if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
	{
		if (pThis->m_nAutoCntPressure[nThIdx] > 0)
		{
			nSocketMax = 0;
			pThis->m_nAutoCntPressure[nThIdx]--;
			if (pThis->m_nAutoCntPressure[nThIdx] > 0)
			{
				pThis->m_nIsAuto[nThIdx] = 0xff;
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx = 0;

				goto PRESSURElOOP;
			}
		}
	}
	return 0;
}
UCHAR gSendbuf5[16 * 1024 * 1024];
UCHAR gReadbuf5[4 * 1024 * 1024];
//四个MAP不同之处
//pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread0, (LPVOID)pThis);
//AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap0, (LPVOID)pThis);
//PRESSURElOOP
//PCEND
//PCCANCEL
//USBERR
DWORD WINAPIV CMainFrame::UsbDataProcFileMap5(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR *pSendbuf = gSendbuf5;
	UCHAR *pReadbuf = gReadbuf5;
	CProgressCtrl *pCProgress = &pThis->pFormView2->m_progress5;
	UINT nSnOfset;

	CTimeSpan Timedif;
	int delay;
	CTime TimeBegin = CTime::GetCurrentTime();
	CTime TimeEnd;

	int len;
	int nThIdx = 5;
	int nBufDfLen;
	TCHAR wszPath[MAX_PATH];
	int nNeedDelKey = 0;
	TCHAR wsztemp[180];

	BYTE inEpAddress = 0x83, outEpAddress = 0x01;
	UCHAR cStatus = PROC_END;
	int base = 0;
	UINT *pInt;
	bool ret = 0;
	CString strtmp, showstr = L"";
	PUCHAR		buffersInput = pReadbuf;
	CCyUSBEndPoint *epBulkOut = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(outEpAddress);
	CCyUSBEndPoint *epBulkIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(0X81);
	CCyUSBEndPoint *epBulkCmdIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(inEpAddress);
	long writelenth = 0;
	long nWarnLed = 0;
	long nScale = 0;
	UCHAR *pcData;
	UINT checksum = 0;
	UINT nCheckSums[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	UINT nBufferIdxRd[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
	long readLenth = 1024 * 1024;
	short wColoridx;
	int wErrMaskinoneproc = 0;
	int nNoticeBlue = 0;
	int nNoticePurple = 0;
	UINT64 llSeekAddr = 0;
	//最高位是1表示是读的BUF.
	UCHAR cBufIdx = 0;
	UCHAR  crCurBufIdx = 0;
	UCHAR  cwCurBufIdx = 0;
	UINT nSeekL = 0;
	USHORT wBufIdx8_Haddr8 = 0;
	if (epBulkOut == NULL || epBulkCmdIn == NULL || epBulkIn == NULL) return 1;
	int i, idx = 0;
	int nSocketSenseMask = 0;
	INT nSocketMax = SOCKETMAX;
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		nSocketMax = 2 * SOCKETMAX;

	for (i = 0; i < nSocketMax; i++)
	{
		//使能的SOCKET都RUN
		if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_RUN;
		}
		else
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_DISABLE;
		}

	}


	g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = SER_PROG_RUNNING;

	int nBtnIdx;
	Sleep(THDLY);
	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_RUN;


	if (0 == pThis->nAutoSenseAutoRun)
	{
		//没选autosense
	//单步或者AUTO 第一步,才需要下载算法。FPGA等。AUTO的后面几步就不需要了//叠料//非空擦除第一次擦除
		if ((pThis->m_nIsAuto[nThIdx] == 0) || ((pThis->m_nIsAuto[nThIdx]) && (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0)) || pThis->stu_overlap.nIsOverLapCheck[nThIdx] ||
			(g_nEraseWhenNOTBlank && ('e' == pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]])))
		{
			ret = pThis->DownloadConfig_GetPincheck(nThIdx);
		}
	}

	else
	{
		//选了AUTOsense，第一次要DownloadConfig_GetPincheck0，之后每个AUTO的第一次只要要SendConfiWord就行
		if ((pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0) || (0 == pThis->nAutoLoopFirst[nThIdx]))
		{
			pThis->pFormView3->RichEditShow(nThIdx, L"Please insert new chips.....", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 20);
			while (1)
			{

				if (0 == pThis->nAutoLoopFirst[nThIdx])
				{
					ret = pThis->DownloadConfig_GetPincheck(nThIdx);
					if (ret)break;

				}
				else
				{
					ret = pThis->SendConfiWord(nThIdx, 3, pThis->m_cDownData[nThIdx], sizeof(pThis->m_cDownData[nThIdx]));
					if (ret)break;
				}
				pThis->PinSenseInAuto(nThIdx, pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
				pThis->pFormView2->SenseBlink(nThIdx);
				for (i = 0; i < SOCKETMAX; i++)
				{
					if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit & (1 << i))
					{
						//第一次接触上就行
						if (pThis->nAutoLoopFirst[nThIdx])
						{
							if (BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}
						else
						{
							//之后要有状态便话，有先取再放的过程
							if ((BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]) || (BLINK_NULL == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]))
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}

					}
				}
				pThis->nAutoLoopFirst[nThIdx] = 1;
				if (nSocketSenseMask == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)break;
				//停止
				if (0 == (pThis->nAutoSenseAutoRunStartEnd % 2))
				{

					memset(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx]));
					//	memset(stu_PinCheckBlink.nStartBlinkArr[i], 0, sizeof(stu_PinCheckBlink.nStartBlinkArr[i]));
					memset(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx]));
					pThis->m_nAutoCntPressure[nThIdx] = 0;
					pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
					pThis->m_pThreadUsbData[nThIdx] = NULL;
					pThis->nAutoSenseAutoRunStartEnd = 0;
					pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
					for (i = 0; i < SOCKETMAX; i++)
					{
						if (BLINK_START == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
						{
							pThis->pFormView2->mp_Static_ModArr[nThIdx][i]->SetIcon(pThis->pFormView2->stu_PinCheckBlink.HiconsavedIcon[nThIdx][i]);
						}
					}
					return 0;

				}
			}
		}
	}
	if (ret)
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		return 0;
	}
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	strtmp += L" BEGIN...";
	pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 30);

	//OVERLAPPED		OutOvLap;
	//UCHAR *outContext;
	//延续上次的错误状态码
	wErrMaskinoneproc |= pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus;
	//传输数据是否512字节的倍数，要处理，否则，传输死机
	char cIs512Multy = 0;
	


	CString path;
	CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[0]);
	path.Format(L"%slib\\%s", g_wszCurPath, wsztemp);
	path += L".bf";
	//创建文件对象
	CFileException e;
	CFile64 wfile;
	CFile64 rfile;
	int nSnChnIdx = 0;
	CFile SnFile;




	//如果是读.开读的文件
	if (pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'r')
	{
		/*if (!wfile.Open(pThis->m_strReadFileDefaultPath[0], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

			return 0;
		}*/
	}
	strtmp = path;
	showstr = pThis->m_strReadFileDefaultPath[0];
	//if (strtmp.MakeUpper() != showstr.MakeUpper())
	{
		if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
			return 0;
		}
	}
	strtmp.Empty();
	showstr.Empty();



	//要注意的是,必须先操作完 pBuffer才能UnmapViewOfFile,
	//如果先UnmapViewOfFile,再操作 pBuffer则会出错,因为pBuffer已经被释放了
	pInt = (UINT*)pSendbuf;
	pcData = (UCHAR *)pSendbuf;

	epBulkOut->Abort();
	epBulkOut->Reset();
	epBulkCmdIn->Abort();
	epBulkCmdIn->Reset();
	epBulkIn->Abort();
	epBulkIn->Reset();

	//strtmp.Format(L"checksum=%u\n", checksum);
	pCProgress->SetRange(0, 100);
	epBulkOut->TimeOut = INFINITE;
	epBulkCmdIn->TimeOut = INFINITE;
	checksum = 0;


	//面板LED显示

	if (pThis->m_pThreadUserProc1[nThIdx] != NULL)
	{
		strtmp.Format(L"site%d thread proc ptr NOT NULL", pThis->m_nSiteNo[nThIdx]);
		AfxMessageBox(strtmp);
	}
	OVERLAPPED ovLapStatus;
	memset(&ovLapStatus, 0, sizeof(OVERLAPPED));
	ovLapStatus.hEvent = CreateEvent(NULL, false, false, NULL);
	int nMutex = 0;
	while (1)
	{
	
	
	 
	   

	    
		
		PUCHAR context = epBulkCmdIn->BeginDataXfer(buffersInput, readLenth, &ovLapStatus);
		if (nMutex == 0)
		{
			nMutex = 1;
			pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread, (LPVOID)&nThIdx);
		}
		
		bool   wResult = epBulkCmdIn->WaitForXfer(&ovLapStatus,INFINITE);
		bool   fResult = epBulkCmdIn->FinishDataXfer(buffersInput, readLenth, &ovLapStatus, context);

	    
		 ret =wResult && fResult;
		 if (ret != true)
		 {
			 CloseHandle(ovLapStatus.hEvent);
			 epBulkCmdIn->Abort();
			 epBulkOut->Abort();
			 //取消映射
			 if (rfile.IsOpen()) rfile.Close();
			 if (wfile.IsOpen()) wfile.Close();
			 pThis->pFormView3->RichEditShow(nThIdx, L"USB data req transfer err", COLOR_RED, 0, 0);
			 //关闭文件映射对象
			 pThis->m_pThreadUsbData[nThIdx] = NULL;
			 return -1;
		 }
		//OUT数据，主要流程，烧录校验
		if (buffersInput[0] == 'O')
		{
			cIs512Multy = buffersInput[1] & 4;
			memcpy(&writelenth, &buffersInput[2], 4);
			//0,1:SINGLE 和双BUFFER的STARTSTORE
			if ((buffersInput[1] & 3) <= 1)
			{
				if (cIs512Multy)
				{
					len=rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}

				//SN
				if ((cBufIdx & 0x7f) == BUFNUM)
				{
					pThis->m_CriticalSectionKey.Lock();

					//[0:3]第几组序列,低4位，,其余是OFFSET
					//[4]删除KEY文件吗
					//[5:31]OFFSET
					nSnChnIdx = llSeekAddr & 0xf;
					nNeedDelKey = ((llSeekAddr >> 4) & 1);
					nSnOfset = llSeekAddr >> 5;
					//取得几个序列号
					if (pThis->stu_GenSetting.nUserSnLen[nSnChnIdx])
					{
						int nSnCnt = writelenth / pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						writelenth = nSnCnt*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						if (writelenth > SIZE16MB - 1)
						{
							writelenth = SIZE2MB - 1;
							pThis->pFormView3->RichEditShow(nThIdx, L"change to 2MB(Key must <2MB)", COLOR_RED, 0, 0);
						}
						pThis->GetOneUserSn(nThIdx, nSnChnIdx, nSnOfset, nNeedDelKey, nSnCnt);
						pcData[0] = pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum;
						memcpy(pcData + 1, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr, writelenth);
						writelenth += 1;
					}
					else
					{
						writelenth = 2;
						memset(pcData, 0, writelenth);
					}

					pThis->m_CriticalSectionKey.Unlock();
				}
				//等待三秒

				epBulkOut->XferData(pcData, writelenth);



			}

#if 1

			//下一次准备
			//memset(pcData, 1, 1024);
			//双buffer

			if ((buffersInput[1] & 2))
			{
				if (cIs512Multy)
				{
					len = rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}



				epBulkOut->XferData(pcData, writelenth);


			}
			//
#endif

		}
		//IN数据，读
		else if (buffersInput[0] == 'I')
		{
			if (wfile.IsClosed())
			{
				if (!wfile.Open(pThis->m_strReadFileDefaultPath[cwCurBufIdx], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
				{
					strtmp.Format(L"Failed to open the file %s\n", e.m_strFileName);
					AfxMessageBox(strtmp);
					epBulkCmdIn->Abort();
					epBulkOut->Abort();

					pThis->m_pThreadUsbData[nThIdx] = NULL;
					return 0;
				}
			}
			if (g_nIsEmmc){pThis->m_nIsLoadBufferDll = 1;pThis->m_nIsReadFitnessNeedDataAnalysis=1;}
			cBufIdx |= 0x80;
			len = wfile.GetPosition();
			//把读之前SEEK的位置加上去
			if (llSeekAddr > len)
			{
				//如果要填充1
				if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cwCurBufIdx & 0x7f], "0"))
				{
					memset(pSendbuf, 0xff, SIZE16MB);
					len = llSeekAddr - len;
					for (i = 0; i < len / SIZE16MB; i++)
					{
						wfile.Write(pSendbuf, SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
					}

					if (len%SIZE16MB)
					{
						wfile.Write(pSendbuf, len%SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
					}

				}
				else
				{
					//直接填0
					wfile.Seek(llSeekAddr, CFile64::begin, 1);
				}


			}

			memcpy(&readLenth, &buffersInput[2], 4);
			ret = epBulkIn->XferData(buffersInput, readLenth);
			if (ret != true)
			{
				CloseHandle(ovLapStatus.hEvent);
				epBulkCmdIn->Abort();
				epBulkOut->Abort();
				epBulkIn->Abort();
				//取消映射
				if (rfile.IsOpen()) rfile.Close();
				if (wfile.IsOpen()) wfile.Close();
				pThis->pFormView3->RichEditShow(nThIdx, L"USB data in transfer err", COLOR_RED, 0, 0);
				//关闭文件映射对象
				pThis->m_pThreadUsbData[nThIdx] = NULL;
				return -1;
			}
			wfile.Write(buffersInput, readLenth);
			nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(buffersInput, readLenth);
			nBufferIdxRd[cwCurBufIdx] = 1;
			len = wfile.GetPosition();
		}
		//正常结束和CANCEL
		else if (buffersInput[0] == 'C')
		{
			if (0 == buffersInput[2])
			{
				//正常退出

				if (0 == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
				{
					//socket号都不对
					pThis->m_nIsAuto[nThIdx] = 0;
					cStatus = PROC_SOCKETALLERR;
				}
				//读追加文件末尾填充
				if (cBufIdx & 0x80)
				{
					if (wfile.IsOpen())
					{
						len = wfile.GetPosition();
						sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f], "%x", &nBufDfLen);
						//要追加填充
						if (nBufDfLen > len)
						{
							//如果要填充1
							if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cBufIdx & 0x7f], "0"))
							{
								len = nBufDfLen - len;
								memset(pSendbuf, 0xff, SIZE16MB);
								for (i = 0; i < len / SIZE16MB; i++)
								{
									wfile.Write(pSendbuf, SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
								}

								if (len%SIZE16MB)
								{
									wfile.Write(pSendbuf, len%SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
								}

							}
							else
							{
								//直接填0
								wfile.Seek(nBufDfLen, CFile64::begin, 1);
							}

						}
					}
					
				}

				//if (cBufIdx & 0x80)
				{
					for (i = 0; i < BUFNUM; i++)
					{
						if (nBufferIdxRd[i])
						{
							CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);

							strtmp.Format(L"%s Checksum=0x%08x", wsztemp, nCheckSums[i]);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
							if (g_nIsEmmc)pThis->pFormView2->DispChecksumInListCtrl(pThis->m_cComboBufSelMap[i], nCheckSums[i], nCheckSums[i]);
						}
					}

				}


				goto PCEND;
			}
			//
			else if (1 == buffersInput[2])
			{
				//cancel
				//	strtmp.Format(L"Cancel thread %s\n", __FUNCTIONW__);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 0, pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit);
				pCProgress->SetPos(0);
				//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				cStatus = PROC_CANCEL;
				pThis->m_nIsAuto[nThIdx] = 0;
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				//pThis->Beep(nThIdx, 0);
				goto PCCANCEL;

			}
			//算法FAIL上报
			else if (2 == buffersInput[2])
			{
				//cancel
				strtmp.Format(L"Fail\n");
				pCProgress->SetPos(0);
				if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				cStatus = PROC_END;
			//	pThis->m_nIsAuto[nThIdx] = 0;
				goto PCEND;

			}

		}
		//DEBUGSTRING
		else if (buffersInput[0] == 'D')
		{
			if (0xff == ((UCHAR)buffersInput[2]))
			{
				int nColor = (buffersInput[3] << 16) | (buffersInput[4] << 8) | (buffersInput[5]);
				CharToTchar(wsztemp, (const char*)(buffersInput + 2 + 4));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, nColor, 0, 0);
			}
			else
			{
				CharToTchar(wsztemp, (const char*)(buffersInput + 2));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
			}


		}
		//进度条 PROGRESS
		else if (buffersInput[0] == 'P')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			pCProgress->SetPos(nScale);
			g_SerialResBuf[SERSOCKBASE + nSocketMax* 32 + (pThis->m_nSiteNo[nThIdx] - 1)] = nScale;

		}
		else if (buffersInput[0] == 'X')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			memcpy(g_ConfigData.nData, &buffersInput[2], 498);

		}
		//BufferSeek
		else if (buffersInput[0] == 'S')
		{

			memcpy(&nSeekL, &buffersInput[2], 4);
			memcpy(&wBufIdx8_Haddr8, &buffersInput[2 + 4], 2);
			llSeekAddr = (UINT64)(wBufIdx8_Haddr8 &0XFF)<< 32| nSeekL;
			cBufIdx = wBufIdx8_Haddr8 >> 8;

			//获得SN
			if ((cBufIdx & 0x7f) == BUFNUM)
			{

			}
			//写操作的BUFFER NUM与大于MAX
			else if (((cBufIdx & 0x7f) > BUFNUM) && ((cBufIdx & 0x80) == 0))
			{
				strtmp.Format(L"Buffer Idx>%d error\n", BUFNUM);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				pThis->Beep(nThIdx, 2);
				goto PCCANCEL;
			}

			//写操作时DEVICE没有这个BUFFER NUMBER
			else if (((cBufIdx & 0x80) == 0) && ((0 == strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[cBufIdx & 0x7f])) || (0 == strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f]))))
			{
				strtmp.Format(L"Buffer Idx %d Invalid\n", cBufIdx);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				goto PCCANCEL;
			}
			else if ((0 == (cBufIdx & 0x80)) && ((cBufIdx & 0X7F) == crCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是写操作

				rfile.Seek(llSeekAddr, CFile64::begin, 1);

			}
			else if ((cBufIdx & 0x80) && ((cBufIdx & 0X7F) == cwCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是读，啥也不干
			}
			//不同要重新打开文件
			else
			{
				//	if (Curfile.IsOpen())
				{
					//无论是否打开，当前读BUFFER idx都要更新
					cwCurBufIdx = cBufIdx & 0X7F;
					//读操作
					if (cBufIdx & 0x80)
					{
						if (wfile.IsOpen())
						{
							wfile.Close();
							strtmp.Format(L"wBuf%d closed", cwCurBufIdx);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
							
							//读直接用路径，不是BUFX
							path = pThis->m_strReadFileDefaultPath[cBufIdx & 0x7f];
							if (rfile.IsOpen())
							{
								if (rfile.GetFileName() == pThis->m_strReadFileDefaultPath[cwCurBufIdx])
								{
									rfile.Close();
								}
							}
							if (!wfile.Open(path, GENERIC_WRITE, 0, OPEN_ALWAYS, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								return 0;
							}
							strtmp.Format(L"buf%d open,seek %d\n", cwCurBufIdx, llSeekAddr);
						}

					}
					//写操作
					else
					{
						if (rfile.IsOpen())
						{
							rfile.Close();
						//	strtmp.Format(L"wBuf%d closed", crCurBufIdx);
							//pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
						}
							crCurBufIdx = cBufIdx & 0X7F;
							CharToTchar(wszPath, pstuDevInfo[g_curDeviceSel].szBufNameArrs[crCurBufIdx]);
							path.Format(L"%slib\\%s", g_wszCurPath, wszPath);
							path += L".bf";
							if (wfile.IsOpen())
							{
								if (wfile.GetFileName() == path)
								{
									wfile.Close();
								}
							}
							if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								return 0;
							}
							rfile.Seek(llSeekAddr, CFile64::begin, 1);
							strtmp.Format(L"buf%d open,seek %d\n", crCurBufIdx, llSeekAddr);
						
					}


					//读的话，需要在读到数据的时候填充，不要直接SEEK，

					//if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);

				}
			}

		}
		//LED状态显示颜色
		else if (buffersInput[0] == 'W')
		{
			memcpy(&nWarnLed, &buffersInput[2], 4);
			//pCProgress->SetPos(nScale);
			wColoridx = nWarnLed >> 16;
			//低16位是掩码

			if (WARNCOLOR_RED == wColoridx)
			{
				//有错误才显示红灯
				for (i = 0; i < nSocketMax; i++)
				{
					if (nWarnLed&(1 << i))
					{
						//重复SOCKET只显示一次
						if (0 == (wErrMaskinoneproc&(1 << i)))
						{
							if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
							{

								strtmp.Format(L"socket%d Failure", i + 1);
								if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 2);
							}

						}

					}
				}
				wErrMaskinoneproc |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_BLUE == wColoridx)
			{
				nNoticeBlue |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticeBlue&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_PURPLE == wColoridx)
			{
				nNoticePurple |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticePurple&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}

			else
			{
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nWarnLed&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}


		}

		if (ret != true)
		{
			pThis->stu_UsbDeviceArr[nThIdx].status = USBNOTCONNECT;

			//SOCKET设置未连接
			g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = USBNOTCONNECT;
			memset(&g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax], SER_SOCKET_DISABLE, nSocketMax);
			memset(&pThis->stu_AutoSeq[nThIdx], 0, sizeof(pThis->stu_AutoSeq[nThIdx]));
			cStatus = PROC_ERRSTOP;
			goto USBERR;

		}

	}

PCEND:
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	//如果选了叠料
	if (pThis->stu_overlap.nIsOverLapCheck[nThIdx])
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Checking", COLOR_YELLOW, 0, 0);
		wErrMaskinoneproc = (~(wErrMaskinoneproc))&(pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
		pThis->stu_overlap.nOverLapSockFail[nThIdx] = wErrMaskinoneproc;

		pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, pThis->stu_overlap.nOverLapSockFail[nThIdx]);
		//如果校验成功，代表叠料了

		if(pThis->stu_overlap.nOverLapSockFail[nThIdx])
		{
			if (pThis->stu_overlap.nOverLapSockFail[nThIdx] == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Check Fail", COLOR_RED, 0, 0);
				
			}
			for (i = 0; i < SOCKETMAX; i++)
			{
				if((1<<i)&(pThis->stu_overlap.nOverLapSockFail[nThIdx] ))
				{
					strtmp.Format(L"Sok %d overlap Fail", i + 1);
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				}
			}
			
		}
		
	}
		
	//如果选了空检查出错擦除，第一步是空检查，都OK的情况下，直接跳过下面的ERASE
	else if((pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'b')&&(g_nEraseWhenNOTBlank))
	{
		if(wErrMaskinoneproc==0)
		{
			pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;						
		}
		//g_nEraseWhenNOTBlank==1在BLANK中ERRMASK不能设置1，否则会导致后面退出
		wErrMaskinoneproc = 0;

	}
	
	//全错，又不是blank且g_nEraseWhenNOTBlank=0，则停止
	if (wErrMaskinoneproc == pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)
	{
		pThis->m_nIsAuto[nThIdx] = 0;
	}
PCCANCEL:
	pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus |= (wErrMaskinoneproc|pThis->stu_overlap.nOverLapSockFail[nThIdx]);

	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
USBERR:
	CloseHandle(ovLapStatus.hEvent);
	epBulkCmdIn->Abort();
	epBulkOut->Abort();
	//CloseHandle(OutOvLap.hEvent);
	//取消映射
	if (rfile.IsOpen())
		rfile.Close();
	if (wfile.IsOpen())
	{
		wfile.Close();
	}


	//关闭文件映射对象

	pThis->m_pThreadUsbData[nThIdx] = NULL;

	if (cStatus == PROC_CANCEL)
	{
		strtmp.Empty();
	}
	//如果SOCKET全部报错。就不报下面这些FINISHED了
	if (cStatus != PROC_SOCKETALLERR)
	{
		if (cStatus == PROC_CANCEL)strtmp += L" Canceled";
		else
		{
			if (0 == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" SUCCESS";;
			}
			else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" FAIL";
			}
			else
				strtmp += L" FINISHED";
		}
		if (0==pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 6);
		TimeEnd = CTime::GetCurrentTime();
		Timedif = TimeEnd - TimeBegin;
		delay = Timedif.GetMinutes() * 60 + Timedif.GetSeconds();
		strtmp.Format(L"%d seconds", delay);
		pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
	}

	if ((cStatus == PROC_END) || (cStatus == PROC_CANCEL))
	{
		//AUTO中
		if (pThis->m_nIsAuto[nThIdx])
		{
			//叠料检测那次不++；
			if (pThis->stu_overlap.nIsOverLapCheck[nThIdx] == 0)
			{
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;
				
			}
			else pThis->stu_overlap.nIsOverLapCheck[nThIdx] = 0;


		PRESSURElOOP:


			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx < pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				//中途掉线就不AUTO哦了
				if (pThis->stu_UsbDeviceArr[nThIdx].status != USBNOTCONNECT)
					AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap5, (LPVOID)pThis);
			}
			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
			}
		}
		//单次或者AUTO最后一次
		if (pThis->m_nIsAuto[nThIdx] == 0)
		{
			//记录本次失败的SOCKET
			pThis->m_FailSktLastAuto[nThIdx] = wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
			if (pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;

				if (0xff == (pThis->m_nBtnIdx & 0xff))
				{//确保是AUTO
					if (0 == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO SUCCESS";
					}
					else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO FAIL";
					}
					else
						strtmp = L"AUTO FINISHED";
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
				}
			}
			//统计
			for (i = 0; i < nSocketMax; i++)
			{
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{

					if ((wErrMaskinoneproc|pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus)&(1 << i))
					{

						pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[i]++;
						pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt++;
					}
					pThis->stu_UsbDeviceArr[nThIdx].nSokTotalCnt[i]++;
					pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt++;
				}
			}
			strtmp.Format(L"Total:%d  Success:%d  Fail:%d", pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt - pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 40);
			strtmp.Format(L"SockFail %d,%d,%d,%d,%d,%d,%d,%d", pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[0], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[1], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[2], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[3], \
				pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[4], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[5], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[6], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[7]);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 0);
			pThis->SummaryLog(nThIdx);
			//根据nSockProgStatus ,失败的写回SN 文件
			//if (nNeedDelKey)
			{
				for (nSnChnIdx = 0; nSnChnIdx < pThis->stu_GenSetting.nCnt; nSnChnIdx++)
				{
					if (pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum > 0)
					{
						idx = 0;
						pThis->m_CriticalSectionLog.Lock();
						for (i = 0; i < SOCKETMAX; i++)
						{
							//SOCKET不为空
							if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit&(1 << i))
							{
								//失败，SN码一一写回
								//失败，从KEYPSD文件夹MOVEBACK
								//char path_buffer[_MAX_PATH];
								TCHAR drive[_MAX_DRIVE];
								TCHAR dir[_MAX_DIR];
								TCHAR fname[_MAX_FNAME];
								TCHAR ext[_MAX_EXT];
								_wsplitpath(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], drive, dir, fname, ext);
								if (pThis->stu_GenSetting.nIsDelete)
								{
									strtmp = g_wszCurPath;
								}
								else
								{
									strtmp = drive;
									strtmp += dir;
								}
								strtmp += L"KPsd\\";
								strtmp += fname;
								strtmp += ext;
								if (0 != (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i)))
								{

								}
								else
								{

									DeleteFile(strtmp);
									if (0 == MoveFile(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], strtmp))
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										strtmp += L" move fail";
										pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

									}
									else
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										if (wcslen(fname))
										{

											strtmp += L" moved";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
											if (pThis->stu_GenSetting.nIsDelete)
											{
												strtmp = g_wszCurPath;
											}
											else
											{
												strtmp = drive;
												strtmp += dir;
											}

											strtmp += L"KPsd\\";

											pThis->logPsdKey4(strtmp, fname);

										}
									}

								}
								idx++;

							}
						}
						pThis->m_CriticalSectionLog.Unlock();
					}

				}
			}

			if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				//全错 FAIL


				pThis->Beep(nThIdx, 2);


			}
			//成功，无错
			else if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->Beep(nThIdx, 0);
			}
			//计算时间
			if (cStatus != PROC_SOCKETALLERR)
			{
				pThis->m_TimeEnd[nThIdx] = CTime::GetCurrentTime();
				Timedif = pThis->m_TimeEnd[nThIdx] - pThis->m_TimeBegin[nThIdx];
				delay = Timedif.GetTotalSeconds();
				strtmp.Format(L"Total %d seconds", delay);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
				pThis->pFormView3->RichEditShow(nThIdx, L"", OPERATIONCOLOR, 0, 0);
			}

			//删除KEY的记录
			for (i = 0; i < 10; i++)
			{
				pThis->stu_UserSNProg[nThIdx][i].nSnNum = 0;
				memset(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile, 0, sizeof(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile));
			}
			pThis->HighZ_CloseV(nThIdx);
		}
	}
	if (pThis->m_nIsAuto[nThIdx] == 0)
	{
		//串口 和网络
		if ((stu_RemoteStat.nRemoteStat > 0) && ((TRUE == stu_RemoteStat.isComOpened) || (pThis->m_SocketObject.IsOpen())))
		{

			

			for (i = 0; i < nSocketMax; i++)
			{
				//使能的SOCKET都RUN
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{
					//失败的
					if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i))
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
					//成功的
					else
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_OK;
					}

				}

				//未使能的，如果是SOCKET ERR=1，是座子号不对
				else
				{
				//	if (pThis->stu_UsbDeviceArr[nThIdx].cSokEncRet[i])
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
				}

			}
			g_SerialResBuf[(pThis->m_nSiteNo[nThIdx] - 1)] = SER_PROG_READY;


		}
		pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus = 0;
	}



	pThis->pFormView1->CntDisplayEachLeftListCtrl(nThIdx, 0);
	pThis->pFormView2->CntDisplayEachPanel(nThIdx);


	//压力测试
	//如果选择PINCHECK AUTO，使用压力测试的流程，把次数固定
	if (pThis->nAutoSenseAutoRun)
	{
		if (pThis->nAutoSenseAutoRunStartEnd % 2)
		{
			pThis->m_nAutoCntPressure[nThIdx] = 5;
		}
		else
		{
			pThis->m_nAutoCntPressure[nThIdx] = 0;
			pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
			pThis->nAutoSenseAutoRunStartEnd = 0;
			pThis->m_pThreadUsbData[nThIdx] = NULL;

		}

	}
	if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
	{
		if (pThis->m_nAutoCntPressure[nThIdx] > 0)
		{
			nSocketMax = 0;
			pThis->m_nAutoCntPressure[nThIdx]--;
			if (pThis->m_nAutoCntPressure[nThIdx] > 0)
			{
				pThis->m_nIsAuto[nThIdx] = 0xff;
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx = 0;

				goto PRESSURElOOP;
			}
		}
	}
	return 0;
}
UCHAR gSendbuf6[16 * 1024 * 1024];
UCHAR gReadbuf6[4 * 1024 * 1024];
//四个MAP不同之处
//pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread0, (LPVOID)pThis);
//AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap0, (LPVOID)pThis);
//PRESSURElOOP
//PCEND
//PCCANCEL
//USBERR
DWORD WINAPIV CMainFrame::UsbDataProcFileMap6(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR *pSendbuf = gSendbuf6;
	UCHAR *pReadbuf = gReadbuf6;
	CProgressCtrl *pCProgress = &pThis->pFormView2->m_progress6;
	UINT nSnOfset;

	CTimeSpan Timedif;
	int delay;
	CTime TimeBegin = CTime::GetCurrentTime();
	CTime TimeEnd;

	int len;
	int nThIdx = 6;
	int nBufDfLen;
	TCHAR wszPath[MAX_PATH];
	int nNeedDelKey = 0;
	TCHAR wsztemp[180];

	BYTE inEpAddress = 0x83, outEpAddress = 0x01;
	UCHAR cStatus = PROC_END;
	int base = 0;
	UINT *pInt;
	bool ret = 0;
	CString strtmp, showstr = L"";
	PUCHAR		buffersInput = pReadbuf;
	CCyUSBEndPoint *epBulkOut = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(outEpAddress);
	CCyUSBEndPoint *epBulkIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(0X81);
	CCyUSBEndPoint *epBulkCmdIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(inEpAddress);
	long writelenth = 0;
	long nWarnLed = 0;
	long nScale = 0;
	UCHAR *pcData;
	UINT checksum = 0;
	UINT nCheckSums[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	UINT nBufferIdxRd[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
	long readLenth = 1024 * 1024;
	short wColoridx;
	int wErrMaskinoneproc = 0;
	int nNoticeBlue = 0;
	int nNoticePurple = 0;
	UINT64 llSeekAddr = 0;
	//最高位是1表示是读的BUF.
	UCHAR cBufIdx = 0;
	UCHAR  crCurBufIdx = 0;
	UCHAR  cwCurBufIdx = 0;
	UINT nSeekL = 0;
	USHORT wBufIdx8_Haddr8 = 0;
	if (epBulkOut == NULL || epBulkCmdIn == NULL || epBulkIn == NULL) return 1;
	int i, idx = 0;
	int nSocketSenseMask = 0;
	INT nSocketMax = SOCKETMAX;
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		nSocketMax = 2 * SOCKETMAX;

	for (i = 0; i < nSocketMax; i++)
	{
		//使能的SOCKET都RUN
		if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_RUN;
		}
		else
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_DISABLE;
		}

	}


	g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = SER_PROG_RUNNING;

	int nBtnIdx;
	Sleep(THDLY);
	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_RUN;


	if (0 == pThis->nAutoSenseAutoRun)
	{
		//没选autosense
	//单步或者AUTO 第一步,才需要下载算法。FPGA等。AUTO的后面几步就不需要了//叠料//非空擦除第一次擦除
		if ((pThis->m_nIsAuto[nThIdx] == 0) || ((pThis->m_nIsAuto[nThIdx]) && (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0)) || pThis->stu_overlap.nIsOverLapCheck[nThIdx] ||
			(g_nEraseWhenNOTBlank && ('e' == pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]])))
		{
			ret = pThis->DownloadConfig_GetPincheck(nThIdx);
		}
	}

	else
	{
		//选了AUTOsense，第一次要DownloadConfig_GetPincheck0，之后每个AUTO的第一次只要要SendConfiWord就行
		if ((pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0) || (0 == pThis->nAutoLoopFirst[nThIdx]))
		{
			pThis->pFormView3->RichEditShow(nThIdx, L"Please insert new chips.....", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 20);
			while (1)
			{

				if (0 == pThis->nAutoLoopFirst[nThIdx])
				{
					ret = pThis->DownloadConfig_GetPincheck(nThIdx);
					if (ret)break;

				}
				else
				{
					ret = pThis->SendConfiWord(nThIdx, 3, pThis->m_cDownData[nThIdx], sizeof(pThis->m_cDownData[nThIdx]));
					if (ret)break;
				}
				pThis->PinSenseInAuto(nThIdx, pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
				pThis->pFormView2->SenseBlink(nThIdx);
				for (i = 0; i < SOCKETMAX; i++)
				{
					if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit & (1 << i))
					{
						//第一次接触上就行
						if (pThis->nAutoLoopFirst[nThIdx])
						{
							if (BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}
						else
						{
							//之后要有状态便话，有先取再放的过程
							if ((BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]) || (BLINK_NULL == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]))
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}

					}
				}
				pThis->nAutoLoopFirst[nThIdx] = 1;
				if (nSocketSenseMask == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)break;
				//停止
				if (0 == (pThis->nAutoSenseAutoRunStartEnd % 2))
				{

					memset(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx]));
					//	memset(stu_PinCheckBlink.nStartBlinkArr[i], 0, sizeof(stu_PinCheckBlink.nStartBlinkArr[i]));
					memset(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx]));
					pThis->m_nAutoCntPressure[nThIdx] = 0;
					pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
					pThis->m_pThreadUsbData[nThIdx] = NULL;
					pThis->nAutoSenseAutoRunStartEnd = 0;
					pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
					for (i = 0; i < SOCKETMAX; i++)
					{
						if (BLINK_START == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
						{
							pThis->pFormView2->mp_Static_ModArr[nThIdx][i]->SetIcon(pThis->pFormView2->stu_PinCheckBlink.HiconsavedIcon[nThIdx][i]);
						}
					}
					return 0;

				}
			}
		}
	}
	if (ret)
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		return 0;
	}
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	strtmp += L" BEGIN...";
	pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 30);

	//OVERLAPPED		OutOvLap;
	//UCHAR *outContext;
	//延续上次的错误状态码
	wErrMaskinoneproc |= pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus;
	//传输数据是否512字节的倍数，要处理，否则，传输死机
	char cIs512Multy = 0;
	


	CString path;
	CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[0]);
	path.Format(L"%slib\\%s", g_wszCurPath, wsztemp);
	path += L".bf";
	//创建文件对象
	CFileException e;
	CFile64 wfile;
	CFile64 rfile;
	int nSnChnIdx = 0;
	CFile SnFile;


	

	//如果是读.开读的文件
	if (pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'r')
	{
		if (!wfile.Open(pThis->m_strReadFileDefaultPath[0], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

			return 0;
		}
	}
	strtmp = path;
	showstr = pThis->m_strReadFileDefaultPath[0];
	//if (strtmp.MakeUpper() != showstr.MakeUpper())
	{
		if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
			return 0;
		}
	}
	strtmp.Empty();
	showstr.Empty();



	//要注意的是,必须先操作完 pBuffer才能UnmapViewOfFile,
	//如果先UnmapViewOfFile,再操作 pBuffer则会出错,因为pBuffer已经被释放了
	pInt = (UINT*)pSendbuf;
	pcData = (UCHAR *)pSendbuf;

	epBulkOut->Abort();
	epBulkOut->Reset();
	epBulkCmdIn->Abort();
	epBulkCmdIn->Reset();
	epBulkIn->Abort();
	epBulkIn->Reset();

	//strtmp.Format(L"checksum=%u\n", checksum);
	pCProgress->SetRange(0, 100);
	epBulkOut->TimeOut = INFINITE;
	epBulkCmdIn->TimeOut = INFINITE;
	checksum = 0;


	//面板LED显示

	if (pThis->m_pThreadUserProc1[nThIdx] != NULL)
	{
		strtmp.Format(L"site%d thread proc ptr NOT NULL", pThis->m_nSiteNo[nThIdx]);
		AfxMessageBox(strtmp);
	}
	OVERLAPPED ovLapStatus;
	memset(&ovLapStatus, 0, sizeof(OVERLAPPED));
	ovLapStatus.hEvent = CreateEvent(NULL, false, false, NULL);
	int nMutex = 0;
	while (1)
	{
	
	
	 
	   

	    
		
		PUCHAR context = epBulkCmdIn->BeginDataXfer(buffersInput, readLenth, &ovLapStatus);
		if (nMutex == 0)
		{
			nMutex = 1;
			pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread, (LPVOID)&nThIdx);
		}
		
		bool   wResult = epBulkCmdIn->WaitForXfer(&ovLapStatus,INFINITE);
		bool   fResult = epBulkCmdIn->FinishDataXfer(buffersInput, readLenth, &ovLapStatus, context);

	    
		 ret =wResult && fResult;
		 if (ret != true)
		 {
			 CloseHandle(ovLapStatus.hEvent);
			 epBulkCmdIn->Abort();
			 epBulkOut->Abort();
			 //取消映射
			 if (rfile.IsOpen()) rfile.Close();
			 if (wfile.IsOpen()) wfile.Close();
			 pThis->pFormView3->RichEditShow(nThIdx, L"USB data req transfer err", COLOR_RED, 0, 0);
			 //关闭文件映射对象
			 pThis->m_pThreadUsbData[nThIdx] = NULL;
			 return -1;
		 }
		//OUT数据，主要流程，烧录校验
		if (buffersInput[0] == 'O')
		{
			cIs512Multy = buffersInput[1] & 4;
			memcpy(&writelenth, &buffersInput[2], 4);
			//0,1:SINGLE 和双BUFFER的STARTSTORE
			if ((buffersInput[1] & 3) <= 1)
			{
				if (cIs512Multy)
				{
					len = rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}

				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}

				//SN
				if ((cBufIdx & 0x7f) == BUFNUM)
				{
					pThis->m_CriticalSectionKey.Lock();

					//[0:3]第几组序列,低4位，,其余是OFFSET
					//[4]删除KEY文件吗
					//[5:31]OFFSET
					nSnChnIdx = llSeekAddr & 0xf;
					nNeedDelKey = ((llSeekAddr >> 4) & 1);
					nSnOfset = llSeekAddr >> 5;
					//取得几个序列号
					if (pThis->stu_GenSetting.nUserSnLen[nSnChnIdx])
					{
						int nSnCnt = writelenth / pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						writelenth = nSnCnt*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						if (writelenth > SIZE16MB - 1)
						{
							writelenth = SIZE2MB - 1;
							pThis->pFormView3->RichEditShow(nThIdx, L"change to 2MB(Key must <2MB)", COLOR_RED, 0, 0);
						}
						pThis->GetOneUserSn(nThIdx, nSnChnIdx, nSnOfset, nNeedDelKey, nSnCnt);
						pcData[0] = pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum;
						memcpy(pcData + 1, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr, writelenth);
						writelenth += 1;
					}
					else
					{
						writelenth = 2;
						memset(pcData, 0, writelenth);
					}

					pThis->m_CriticalSectionKey.Unlock();
				}
				//等待三秒

				epBulkOut->XferData(pcData, writelenth);



			}

#if 1

			//下一次准备
			//memset(pcData, 1, 1024);
			//双buffer

			if ((buffersInput[1] & 2))
			{
				if (cIs512Multy)
				{
					len = rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}



				epBulkOut->XferData(pcData, writelenth);


			}
			//
#endif

		}
		//IN数据，读
		else if (buffersInput[0] == 'I')
		{
			if (wfile.IsClosed())
			{
				if (!wfile.Open(pThis->m_strReadFileDefaultPath[cwCurBufIdx], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
				{
					strtmp.Format(L"Failed to open the file %s\n", e.m_strFileName);
					AfxMessageBox(strtmp);
					epBulkCmdIn->Abort();
					epBulkOut->Abort();

					pThis->m_pThreadUsbData[nThIdx] = NULL;
					return 0;
				}
			}
			if (g_nIsEmmc){pThis->m_nIsLoadBufferDll = 1;pThis->m_nIsReadFitnessNeedDataAnalysis=1;}
			cBufIdx |= 0x80;
			len = wfile.GetPosition();
			//把读之前SEEK的位置加上去
			if (llSeekAddr > len)
			{
				//如果要填充1
				if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cwCurBufIdx & 0x7f], "0"))
				{
					memset(pSendbuf, 0xff, SIZE16MB);
					len = llSeekAddr - len;
					for (i = 0; i < len / SIZE16MB; i++)
					{
						wfile.Write(pSendbuf, SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
					}

					if (len%SIZE16MB)
					{
						wfile.Write(pSendbuf, len%SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
					}

				}
				else
				{
					//直接填0
					wfile.Seek(llSeekAddr, CFile64::begin, 1);
				}


			}

			memcpy(&readLenth, &buffersInput[2], 4);
			ret = epBulkIn->XferData(buffersInput, readLenth);
			if (ret != true)
			{
				CloseHandle(ovLapStatus.hEvent);
				epBulkCmdIn->Abort();
				epBulkOut->Abort();
				epBulkIn->Abort();
				//取消映射
				if (rfile.IsOpen()) rfile.Close();
				if (wfile.IsOpen()) wfile.Close();
				pThis->pFormView3->RichEditShow(nThIdx, L"USB data in transfer err", COLOR_RED, 0, 0);
				//关闭文件映射对象
				pThis->m_pThreadUsbData[nThIdx] = NULL;
				return -1;
			}
			wfile.Write(buffersInput, readLenth);
			nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(buffersInput, readLenth);
			nBufferIdxRd[cwCurBufIdx] = 1;
			len = wfile.GetPosition();
		}
		//正常结束和CANCEL
		else if (buffersInput[0] == 'C')
		{
			if (0 == buffersInput[2])
			{
				//正常退出

				if (0 == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
				{
					//socket号都不对
					pThis->m_nIsAuto[nThIdx] = 0;
					cStatus = PROC_SOCKETALLERR;
				}
				//读追加文件末尾填充
				if (cBufIdx & 0x80)
				{
					if (wfile.IsOpen())
					{
						len = wfile.GetPosition();
						sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f], "%x", &nBufDfLen);
						//要追加填充
						if (nBufDfLen > len)
						{
							//如果要填充1
							if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cBufIdx & 0x7f], "0"))
							{
								len = nBufDfLen - len;
								memset(pSendbuf, 0xff, SIZE16MB);
								for (i = 0; i < len / SIZE16MB; i++)
								{
									wfile.Write(pSendbuf, SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
								}

								if (len%SIZE16MB)
								{
									wfile.Write(pSendbuf, len%SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
								}

							}
							else
							{
								//直接填0
								wfile.Seek(nBufDfLen, CFile64::begin, 1);
							}

						}
					}
					
				}

				//if (cBufIdx & 0x80)
				{
					for (i = 0; i < BUFNUM; i++)
					{
						if (nBufferIdxRd[i])
						{
							CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);

							strtmp.Format(L"%s Checksum=0x%08x", wsztemp, nCheckSums[i]);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
							if (g_nIsEmmc)pThis->pFormView2->DispChecksumInListCtrl(pThis->m_cComboBufSelMap[i], nCheckSums[i], nCheckSums[i]);
						}
					}

				}


				goto PCEND;
			}
			//
			else if (1 == buffersInput[2])
			{
				//cancel
				//	strtmp.Format(L"Cancel thread %s\n", __FUNCTIONW__);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 0, pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit);
				pCProgress->SetPos(0);
				//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				cStatus = PROC_CANCEL;
				pThis->m_nIsAuto[nThIdx] = 0;
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				//pThis->Beep(nThIdx, 0);
				goto PCCANCEL;

			}
			//算法FAIL上报
			else if (2 == buffersInput[2])
			{
				//cancel
				strtmp.Format(L"Fail\n");
				pCProgress->SetPos(0);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				cStatus = PROC_END;
				//	pThis->m_nIsAuto[nThIdx] = 0;
				goto PCEND;

			}

		}
		//DEBUGSTRING
		else if (buffersInput[0] == 'D')
		{
			if (0xff == ((UCHAR)buffersInput[2]))
			{
				int nColor = (buffersInput[3] << 16) | (buffersInput[4] << 8) | (buffersInput[5]);
				CharToTchar(wsztemp, (const char*)(buffersInput + 2 + 4));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, nColor, 0, 0);
			}
			else
			{
				CharToTchar(wsztemp, (const char*)(buffersInput + 2));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
			}


		}
		//进度条 PROGRESS
		else if (buffersInput[0] == 'P')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			pCProgress->SetPos(nScale);
			g_SerialResBuf[SERSOCKBASE + nSocketMax* 32 + (pThis->m_nSiteNo[nThIdx] - 1)] = nScale;

		}
		else if (buffersInput[0] == 'X')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			memcpy(g_ConfigData.nData, &buffersInput[2], 498);

		}
		//BufferSeek
		else if (buffersInput[0] == 'S')
		{

			memcpy(&nSeekL, &buffersInput[2], 4);
			memcpy(&wBufIdx8_Haddr8, &buffersInput[2 + 4], 2);
			llSeekAddr = (UINT64)(wBufIdx8_Haddr8 &0XFF)<< 32| nSeekL;
			cBufIdx = wBufIdx8_Haddr8 >> 8;

			//获得SN
			if ((cBufIdx & 0x7f) == BUFNUM)
			{

			}
			//写操作的BUFFER NUM与大于MAX
			else if (((cBufIdx & 0x7f) > BUFNUM) && ((cBufIdx & 0x80) == 0))
			{
				strtmp.Format(L"Buffer Idx>%d error\n", BUFNUM);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				pThis->Beep(nThIdx, 2);
				goto PCCANCEL;
			}

			//写操作时DEVICE没有这个BUFFER NUMBER
			else if (((cBufIdx & 0x80) == 0) && ((0 == strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[cBufIdx & 0x7f])) || (0 == strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f]))))
			{
				strtmp.Format(L"Buffer Idx %d Invalid\n", cBufIdx);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				goto PCCANCEL;
			}
			else if ((0 == (cBufIdx & 0x80)) && ((cBufIdx & 0X7F) == crCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是写操作

				rfile.Seek(llSeekAddr, CFile64::begin, 1);

			}
			else if ((cBufIdx & 0x80) && ((cBufIdx & 0X7F) == cwCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是读，啥也不干
			}
			//不同要重新打开文件
			else
			{
				//	if (Curfile.IsOpen())
				{
					//无论是否打开，当前读BUFFER idx都要更新
					cwCurBufIdx = cBufIdx & 0X7F;
					//读操作
					if (cBufIdx & 0x80)
					{
						if (wfile.IsOpen())
						{
							wfile.Close();
							strtmp.Format(L"wBuf%d closed", cwCurBufIdx);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
							
							//读直接用路径，不是BUFX
							path = pThis->m_strReadFileDefaultPath[cBufIdx & 0x7f];
							if (rfile.IsOpen())
							{
								if (rfile.GetFileName() == pThis->m_strReadFileDefaultPath[cwCurBufIdx])
								{
									rfile.Close();
								}
							}
							if (!wfile.Open(path, GENERIC_WRITE, 0, OPEN_ALWAYS, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								return 0;
							}
							strtmp.Format(L"buf%d open,seek %d\n", cwCurBufIdx, llSeekAddr);
						}

					}
					//写操作
					else
					{
						if (rfile.IsOpen())
						{
							rfile.Close();
							//strtmp.Format(L"wBuf%d closed", crCurBufIdx);
							//pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
						}
							crCurBufIdx = cBufIdx & 0X7F;
							CharToTchar(wszPath, pstuDevInfo[g_curDeviceSel].szBufNameArrs[crCurBufIdx]);
							path.Format(L"%slib\\%s", g_wszCurPath, wszPath);
							path += L".bf";
							if (wfile.IsOpen())
							{
								if (wfile.GetFileName() == path)
								{
									wfile.Close();
								}
							}
							if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								return 0;
							}
							rfile.Seek(llSeekAddr, CFile64::begin, 1);
							strtmp.Format(L"buf%d open,seek %d\n", crCurBufIdx, llSeekAddr);
						
					}


					//读的话，需要在读到数据的时候填充，不要直接SEEK，

				//	if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);

				}
			}

		}
		//LED状态显示颜色
		else if (buffersInput[0] == 'W')
		{
			memcpy(&nWarnLed, &buffersInput[2], 4);
			//pCProgress->SetPos(nScale);
			wColoridx = nWarnLed >> 16;
			//低16位是掩码

			if (WARNCOLOR_RED == wColoridx)
			{
				//有错误才显示红灯
				for (i = 0; i < nSocketMax; i++)
				{
					if (nWarnLed&(1 << i))
					{
						//重复SOCKET只显示一次
						if (0 == (wErrMaskinoneproc&(1 << i)))
						{
							if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
							{

								strtmp.Format(L"socket%d Failure", i + 1);
								if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 2);
							}

						}

					}
				}
				wErrMaskinoneproc |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_BLUE == wColoridx)
			{
				nNoticeBlue |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticeBlue&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_PURPLE == wColoridx)
			{
				nNoticePurple |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticePurple&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}

			else
			{
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nWarnLed&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}


		}

		if (ret != true)
		{
			pThis->stu_UsbDeviceArr[nThIdx].status = USBNOTCONNECT;

			//SOCKET设置未连接
			g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = USBNOTCONNECT;
			memset(&g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax], SER_SOCKET_DISABLE, nSocketMax);
			memset(&pThis->stu_AutoSeq[nThIdx], 0, sizeof(pThis->stu_AutoSeq[nThIdx]));
			cStatus = PROC_ERRSTOP;
			goto USBERR;

		}

	}

PCEND:
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	//如果选了叠料
	if (pThis->stu_overlap.nIsOverLapCheck[nThIdx])
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Checking", COLOR_YELLOW, 0, 0);
		wErrMaskinoneproc = (~(wErrMaskinoneproc))&(pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
		pThis->stu_overlap.nOverLapSockFail[nThIdx] = wErrMaskinoneproc;

		pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, pThis->stu_overlap.nOverLapSockFail[nThIdx]);
		//如果校验成功，代表叠料了

		if (pThis->stu_overlap.nOverLapSockFail[nThIdx])
		{
			if (pThis->stu_overlap.nOverLapSockFail[nThIdx] == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Check Fail", COLOR_RED, 0, 0);

			}
			for (i = 0; i < SOCKETMAX; i++)
			{
				if ((1 << i)&(pThis->stu_overlap.nOverLapSockFail[nThIdx]))
				{
					strtmp.Format(L"Sok %d overlap Fail", i + 1);
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				}
			}

		}

	}

	//如果选了空检查出错擦除，第一步是空检查，都OK的情况下，直接跳过下面的ERASE
	else if ((pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'b') && (g_nEraseWhenNOTBlank))
	{
		if (wErrMaskinoneproc == 0)
		{
			pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;
		}
		//g_nEraseWhenNOTBlank==1在BLANK中ERRMASK不能设置1，否则会导致后面退出
		wErrMaskinoneproc = 0;

	}

	//全错，又不是blank且g_nEraseWhenNOTBlank=0，则停止
	if (wErrMaskinoneproc == pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)
	{
		pThis->m_nIsAuto[nThIdx] = 0;
	}
PCCANCEL:
	pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus |= (wErrMaskinoneproc | pThis->stu_overlap.nOverLapSockFail[nThIdx]);


	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
USBERR:
	CloseHandle(ovLapStatus.hEvent);
	epBulkCmdIn->Abort();
	epBulkOut->Abort();
	//CloseHandle(OutOvLap.hEvent);
	//取消映射
	if (rfile.IsOpen())
		rfile.Close();
	if (wfile.IsOpen())
	{
		wfile.Close();
	}


	//关闭文件映射对象

	pThis->m_pThreadUsbData[nThIdx] = NULL;

	if (cStatus == PROC_CANCEL)
	{
		strtmp.Empty();
	}
	//如果SOCKET全部报错。就不报下面这些FINISHED了
	if (cStatus != PROC_SOCKETALLERR)
	{
		if (cStatus == PROC_CANCEL)strtmp += L" Canceled";
		else
		{
			if (0 == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" SUCCESS";;
			}
			else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" FAIL";
			}
			else
				strtmp += L" FINISHED";
		}
		if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 6);
		TimeEnd = CTime::GetCurrentTime();
		Timedif = TimeEnd - TimeBegin;
		delay = Timedif.GetMinutes() * 60 + Timedif.GetSeconds();
		strtmp.Format(L"%d seconds", delay);
		pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
	}

	if ((cStatus == PROC_END) || (cStatus == PROC_CANCEL))
	{
		//AUTO中
		if (pThis->m_nIsAuto[nThIdx])
		{
			//叠料检测那次不++；
			if (pThis->stu_overlap.nIsOverLapCheck[nThIdx] == 0)
			{
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;

			}
			else pThis->stu_overlap.nIsOverLapCheck[nThIdx] = 0;


		PRESSURElOOP:


			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx < pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				//中途掉线就不AUTO哦了
				if (pThis->stu_UsbDeviceArr[nThIdx].status != USBNOTCONNECT)
					AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap6, (LPVOID)pThis);
			}
			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
			}
		}
		//单次或者AUTO最后一次
		if (pThis->m_nIsAuto[nThIdx] == 0)
		{
			//记录本次失败的SOCKET
			pThis->m_FailSktLastAuto[nThIdx] = wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
			if (pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;

				if (0xff == (pThis->m_nBtnIdx & 0xff))
				{//确保是AUTO
					if (0 == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO SUCCESS";
					}
					else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO FAIL";
					}
					else
						strtmp = L"AUTO FINISHED";
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
				}
			}
			//统计
			for (i = 0; i < nSocketMax; i++)
			{
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{

					if ((wErrMaskinoneproc | pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus)&(1 << i))
					{

						pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[i]++;
						pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt++;
					}
					pThis->stu_UsbDeviceArr[nThIdx].nSokTotalCnt[i]++;
					pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt++;
				}
			}
			strtmp.Format(L"Total:%d  Success:%d  Fail:%d", pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt - pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 40);
			strtmp.Format(L"SockFail %d,%d,%d,%d,%d,%d,%d,%d", pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[0], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[1], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[2], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[3], \
				pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[4], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[5], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[6], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[7]);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 0);
			pThis->SummaryLog(nThIdx);
			//根据nSockProgStatus ,失败的写回SN 文件
			//if (nNeedDelKey)
			{
				for (nSnChnIdx = 0; nSnChnIdx < pThis->stu_GenSetting.nCnt; nSnChnIdx++)
				{
					if (pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum > 0)
					{
						idx = 0;
						pThis->m_CriticalSectionLog.Lock();
						for (i = 0; i < SOCKETMAX; i++)
						{
							//SOCKET不为空
							if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit&(1 << i))
							{
								//失败，SN码一一写回
								//失败，从KEYPSD文件夹MOVEBACK
								//char path_buffer[_MAX_PATH];
								TCHAR drive[_MAX_DRIVE];
								TCHAR dir[_MAX_DIR];
								TCHAR fname[_MAX_FNAME];
								TCHAR ext[_MAX_EXT];
								_wsplitpath(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], drive, dir, fname, ext);
								if (pThis->stu_GenSetting.nIsDelete)
								{
									strtmp = g_wszCurPath;
								}
								else
								{
									strtmp = drive;
									strtmp += dir;
								}
								strtmp += L"KPsd\\";
								strtmp += fname;
								strtmp += ext;
								if (0 != (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i)))
								{
#if 0
									if (0 != wcslen(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx]))
									{


										if (0 == MoveFile(strtmp, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx]))
										{
											strtmp.Format(L"Skt%d,", i + 1);
											strtmp += fname;
											strtmp += L" move back fail";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

										}
										else
										{
											strtmp.Format(L"Skt%d,", i + 1);
											strtmp += fname;
											strtmp += L" move backed";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
										}
										//SnFile.Open(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], CFile::modeCreate | CFile::modeWrite);
										//SnFile.Write(&pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr[idx*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx]], pThis->stu_GenSetting.nUserSnLen[nSnChnIdx]);
										//SnFile.Close();

									}

									else
									{
										/*AfxMessageBox(L"SN Number empty");
										pThis->m_CriticalSectionSnRd.Unlock();
										break;*/
									}
#endif
								}
								else
								{

									DeleteFile(strtmp);
									if (0 == MoveFile(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], strtmp))
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										strtmp += L" move fail";
										pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

									}
									else
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										if (wcslen(fname))
										{

											strtmp += L" moved";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
											if (pThis->stu_GenSetting.nIsDelete)
											{
												strtmp = g_wszCurPath;
											}
											else
											{
												strtmp = drive;
												strtmp += dir;
											}

											strtmp += L"KPsd\\";

											pThis->logPsdKey4(strtmp, fname);

										}
									}

								}
								idx++;

							}
						}
						pThis->m_CriticalSectionLog.Unlock();
					}

				}
			}

			if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				//全错 FAIL


				pThis->Beep(nThIdx, 2);


			}
			//成功，无错
			else if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->Beep(nThIdx, 0);
			}
			//计算时间
			if (cStatus != PROC_SOCKETALLERR)
			{
				pThis->m_TimeEnd[nThIdx] = CTime::GetCurrentTime();
				Timedif = pThis->m_TimeEnd[nThIdx] - pThis->m_TimeBegin[nThIdx];
				delay = Timedif.GetTotalSeconds();
				strtmp.Format(L"Total %d seconds", delay);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
				pThis->pFormView3->RichEditShow(nThIdx, L"", OPERATIONCOLOR, 0, 0);
			}

			//删除KEY的记录
			for (i = 0; i < 10; i++)
			{
				pThis->stu_UserSNProg[nThIdx][i].nSnNum = 0;
				memset(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile, 0, sizeof(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile));
			}
			pThis->HighZ_CloseV(nThIdx);
		}
	}
	if (pThis->m_nIsAuto[nThIdx] == 0)
	{
		//串口 和网络
		if ((stu_RemoteStat.nRemoteStat > 0) && ((TRUE == stu_RemoteStat.isComOpened) || (pThis->m_SocketObject.IsOpen())))
		{

			

			for (i = 0; i < nSocketMax; i++)
			{
				//使能的SOCKET都RUN
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{
					//失败的
					if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i))
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
					//成功的
					else
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_OK;
					}

				}

				//未使能的，如果是SOCKET ERR=1，是座子号不对
				else
				{
				//	if (pThis->stu_UsbDeviceArr[nThIdx].cSokEncRet[i])
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
				}

			}
			g_SerialResBuf[(pThis->m_nSiteNo[nThIdx] - 1)] = SER_PROG_READY;


		}
		pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus = 0;
	}



	pThis->pFormView1->CntDisplayEachLeftListCtrl(nThIdx, 0);
	//pThis->pFormView2->CntDisplayEachPanel(nThIdx);


	//压力测试
	//如果选择PINCHECK AUTO，使用压力测试的流程，把次数固定
	if (pThis->nAutoSenseAutoRun)
	{
		if (pThis->nAutoSenseAutoRunStartEnd % 2)
		{
			pThis->m_nAutoCntPressure[nThIdx] = 5;
		}
		else
		{
			pThis->m_nAutoCntPressure[nThIdx] = 0;
			pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
			pThis->nAutoSenseAutoRunStartEnd = 0;
			pThis->m_pThreadUsbData[nThIdx] = NULL;

		}

	}
	if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
	{
		if (pThis->m_nAutoCntPressure[nThIdx] > 0)
		{
			nSocketMax = 0;
			pThis->m_nAutoCntPressure[nThIdx]--;
			if (pThis->m_nAutoCntPressure[nThIdx] > 0)
			{
				pThis->m_nIsAuto[nThIdx] = 0xff;
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx = 0;

				goto PRESSURElOOP;
			}
		}
	}
	return 0;
}
UCHAR gSendbuf7[16 * 1024 * 1024];
UCHAR gReadbuf7[4 * 1024 * 1024];
//四个MAP不同之处
//pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread0, (LPVOID)pThis);
//AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap0, (LPVOID)pThis);
//PRESSURElOOP
//PCEND
//PCCANCEL
//USBERR
DWORD WINAPIV CMainFrame::UsbDataProcFileMap7(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR *pSendbuf = gSendbuf7;
	UCHAR *pReadbuf = gReadbuf7;
	CProgressCtrl *pCProgress = &pThis->pFormView2->m_progress7;
	UINT nSnOfset;

	CTimeSpan Timedif;
	int delay;
	CTime TimeBegin = CTime::GetCurrentTime();
	CTime TimeEnd;

	int len;
	int nThIdx = 7;
	int nBufDfLen;
	TCHAR wszPath[MAX_PATH];
	int nNeedDelKey = 0;
	TCHAR wsztemp[180];

	BYTE inEpAddress = 0x83, outEpAddress = 0x01;
	UCHAR cStatus = PROC_END;
	int base = 0;
	UINT *pInt;
	bool ret = 0;
	CString strtmp, showstr = L"";
	PUCHAR		buffersInput = pReadbuf;
	CCyUSBEndPoint *epBulkOut = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(outEpAddress);
	CCyUSBEndPoint *epBulkIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(0X81);
	CCyUSBEndPoint *epBulkCmdIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(inEpAddress);
	long writelenth = 0;
	long nWarnLed = 0;
	long nScale = 0;
	UCHAR *pcData;
	UINT checksum = 0;
	UINT nCheckSums[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	UINT nBufferIdxRd[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
	long readLenth = 1024 * 1024;
	short wColoridx;
	int wErrMaskinoneproc = 0;
	int nNoticeBlue = 0;
	int nNoticePurple = 0;
	UINT64 llSeekAddr = 0;
	//最高位是1表示是读的BUF.
	UCHAR cBufIdx = 0;
	UCHAR  crCurBufIdx = 0;
	UCHAR  cwCurBufIdx = 0;
	UINT nSeekL = 0;
	USHORT wBufIdx8_Haddr8 = 0;
	if (epBulkOut == NULL || epBulkCmdIn == NULL || epBulkIn == NULL) return 1;
	int i, idx = 0;
	int nSocketSenseMask = 0;
	INT nSocketMax = SOCKETMAX;
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		nSocketMax = 2 * SOCKETMAX;
	
	for (i = 0; i < nSocketMax; i++)
	{
		//使能的SOCKET都RUN
		if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_RUN;
		}
		else
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_DISABLE;
		}

	}


	g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = SER_PROG_RUNNING;

	int nBtnIdx;
	Sleep(THDLY);
	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_RUN;


	if (0 == pThis->nAutoSenseAutoRun)
	{
		//没选autosense
	//单步或者AUTO 第一步,才需要下载算法。FPGA等。AUTO的后面几步就不需要了//叠料//非空擦除第一次擦除
		if ((pThis->m_nIsAuto[nThIdx] == 0) || ((pThis->m_nIsAuto[nThIdx]) && (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0)) || pThis->stu_overlap.nIsOverLapCheck[nThIdx] ||
			(g_nEraseWhenNOTBlank && ('e' == pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]])))
		{
			ret = pThis->DownloadConfig_GetPincheck(nThIdx);
		}
	}

	else
	{
		//选了AUTOsense，第一次要DownloadConfig_GetPincheck0，之后每个AUTO的第一次只要要SendConfiWord就行
		if ((pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0) || (0 == pThis->nAutoLoopFirst[nThIdx]))
		{
			pThis->pFormView3->RichEditShow(nThIdx, L"Please insert new chips.....", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 20);
			while (1)
			{

				if (0 == pThis->nAutoLoopFirst[nThIdx])
				{
					ret = pThis->DownloadConfig_GetPincheck(nThIdx);
					if (ret)break;

				}
				else
				{
					ret = pThis->SendConfiWord(nThIdx, 3, pThis->m_cDownData[nThIdx], sizeof(pThis->m_cDownData[nThIdx]));
					if (ret)break;
				}
				pThis->PinSenseInAuto(nThIdx, pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
				pThis->pFormView2->SenseBlink(nThIdx);
				for (i = 0; i < SOCKETMAX; i++)
				{
					if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit & (1 << i))
					{
						//第一次接触上就行
						if (pThis->nAutoLoopFirst[nThIdx])
						{
							if (BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}
						else
						{
							//之后要有状态便话，有先取再放的过程
							if ((BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]) || (BLINK_NULL == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]))
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}

					}
				}
				pThis->nAutoLoopFirst[nThIdx] = 1;
				if (nSocketSenseMask == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)break;
				//停止
				if (0 == (pThis->nAutoSenseAutoRunStartEnd % 2))
				{

					memset(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx]));
					//	memset(stu_PinCheckBlink.nStartBlinkArr[i], 0, sizeof(stu_PinCheckBlink.nStartBlinkArr[i]));
					memset(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx]));
					pThis->m_nAutoCntPressure[nThIdx] = 0;
					pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
					pThis->m_pThreadUsbData[nThIdx] = NULL;
					pThis->nAutoSenseAutoRunStartEnd = 0;
					pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
					for (i = 0; i < SOCKETMAX; i++)
					{
						if (BLINK_START == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
						{
							pThis->pFormView2->mp_Static_ModArr[nThIdx][i]->SetIcon(pThis->pFormView2->stu_PinCheckBlink.HiconsavedIcon[nThIdx][i]);
						}
					}
					return 0;

				}
			}
		}
	}
	if (ret)
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		return 0;
	}
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	strtmp += L" BEGIN...";
	pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 30);

	//OVERLAPPED		OutOvLap;
	//UCHAR *outContext;
	//延续上次的错误状态码
	wErrMaskinoneproc |= pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus;
	//传输数据是否512字节的倍数，要处理，否则，传输死机
	char cIs512Multy = 0;
	


	CString path;
	CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[0]);
	path.Format(L"%slib\\%s", g_wszCurPath, wsztemp);
	path += L".bf";
	//创建文件对象
	CFileException e;
	CFile64 wfile;
	CFile64 rfile;
	int nSnChnIdx = 0;
	CFile SnFile;


	//如果是读.开读的文件
	if (pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'r')
	{
		if (!wfile.Open(pThis->m_strReadFileDefaultPath[0], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

			return 0;
		}
	}


	strtmp = path;
	showstr = pThis->m_strReadFileDefaultPath[0];
	//if (strtmp.MakeUpper() != showstr.MakeUpper())
	{
		if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
			return 0;
		}
	}
	strtmp.Empty();
	showstr.Empty();


	//要注意的是,必须先操作完 pBuffer才能UnmapViewOfFile,
	//如果先UnmapViewOfFile,再操作 pBuffer则会出错,因为pBuffer已经被释放了
	pInt = (UINT*)pSendbuf;
	pcData = (UCHAR *)pSendbuf;

	epBulkOut->Abort();
	epBulkOut->Reset();
	epBulkCmdIn->Abort();
	epBulkCmdIn->Reset();
	epBulkIn->Abort();
	epBulkIn->Reset();

	//strtmp.Format(L"checksum=%u\n", checksum);
	pCProgress->SetRange(0, 100);
	epBulkOut->TimeOut = INFINITE;
	epBulkCmdIn->TimeOut = INFINITE;
	checksum = 0;


	//面板LED显示

	if (pThis->m_pThreadUserProc1[nThIdx] != NULL)
	{
		strtmp.Format(L"site%d thread proc ptr NOT NULL", pThis->m_nSiteNo[nThIdx]);
		AfxMessageBox(strtmp);
	}
	OVERLAPPED ovLapStatus;
	memset(&ovLapStatus, 0, sizeof(OVERLAPPED));
	ovLapStatus.hEvent = CreateEvent(NULL, false, false, NULL);
	int nMutex = 0;
	while (1)
	{
	
	
	 
	   

	    
		
		PUCHAR context = epBulkCmdIn->BeginDataXfer(buffersInput, readLenth, &ovLapStatus);
		if (nMutex == 0)
		{
			nMutex = 1;
			pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread, (LPVOID)&nThIdx);
		}
		
		bool   wResult = epBulkCmdIn->WaitForXfer(&ovLapStatus,INFINITE);
		bool   fResult = epBulkCmdIn->FinishDataXfer(buffersInput, readLenth, &ovLapStatus, context);

	    
		 ret =wResult && fResult;
		 if (ret != true)
		 {
			 CloseHandle(ovLapStatus.hEvent);
			 epBulkCmdIn->Abort();
			 epBulkOut->Abort();
			 //取消映射
			 if (rfile.IsOpen()) rfile.Close();
			 if (wfile.IsOpen()) wfile.Close();
			 pThis->pFormView3->RichEditShow(nThIdx, L"USB data req transfer err", COLOR_RED, 0, 0);
			 //关闭文件映射对象
			 pThis->m_pThreadUsbData[nThIdx] = NULL;
			 return -1;
		 }
		//OUT数据，主要流程，烧录校验
		if (buffersInput[0] == 'O')
		{
			cIs512Multy = buffersInput[1] & 4;
			memcpy(&writelenth, &buffersInput[2], 4);
			//0,1:SINGLE 和双BUFFER的STARTSTORE
			if ((buffersInput[1] & 3) <= 1)
			{
				if (cIs512Multy)
				{
					len = rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}

				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}

				//SN
				if ((cBufIdx & 0x7f) == BUFNUM)
				{
					pThis->m_CriticalSectionKey.Lock();

					//[0:3]第几组序列,低4位，,其余是OFFSET
					//[4]删除KEY文件吗
					//[5:31]OFFSET
					nSnChnIdx = llSeekAddr & 0xf;
					nNeedDelKey = ((llSeekAddr >> 4) & 1);
					nSnOfset = llSeekAddr >> 5;
					//取得几个序列号
					if (pThis->stu_GenSetting.nUserSnLen[nSnChnIdx])
					{
						int nSnCnt = writelenth / pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						writelenth = nSnCnt*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						if (writelenth > SIZE16MB - 1)
						{
							writelenth = SIZE2MB - 1;
							pThis->pFormView3->RichEditShow(nThIdx, L"change to 2MB(Key must <2MB)", COLOR_RED, 0, 0);
						}
						pThis->GetOneUserSn(nThIdx, nSnChnIdx, nSnOfset, nNeedDelKey, nSnCnt);
						pcData[0] = pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum;
						memcpy(pcData + 1, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr, writelenth);
						writelenth += 1;
					}
					else
					{
						writelenth = 2;
						memset(pcData, 0, writelenth);
					}

					pThis->m_CriticalSectionKey.Unlock();
				}
				//等待三秒

				epBulkOut->XferData(pcData, writelenth);



			}

#if 1

			//下一次准备
			//memset(pcData, 1, 1024);
			//双buffer

			if ((buffersInput[1] & 2))
			{
				if (cIs512Multy)
				{
					len = rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}



				epBulkOut->XferData(pcData, writelenth);


			}
			//
#endif

		}
		//IN数据，读
		else if (buffersInput[0] == 'I')
		{
			if (wfile.IsClosed())
			{
				if (!wfile.Open(pThis->m_strReadFileDefaultPath[cwCurBufIdx], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
				{
					strtmp.Format(L"Failed to open the file %s\n", e.m_strFileName);
					AfxMessageBox(strtmp);
					epBulkCmdIn->Abort();
					epBulkOut->Abort();

					pThis->m_pThreadUsbData[nThIdx] = NULL;
					return 0;
				}
			}
			if (g_nIsEmmc){pThis->m_nIsLoadBufferDll = 1;pThis->m_nIsReadFitnessNeedDataAnalysis=1;}
			cBufIdx |= 0x80;
			len = wfile.GetPosition();
			//把读之前SEEK的位置加上去
			if (llSeekAddr > len)
			{
				//如果要填充1
				if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cwCurBufIdx & 0x7f], "0"))
				{
					memset(pSendbuf, 0xff, SIZE16MB);
					len = llSeekAddr - len;
					for (i = 0; i < len / SIZE16MB; i++)
					{
						wfile.Write(pSendbuf, SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
					}

					if (len%SIZE16MB)
					{
						wfile.Write(pSendbuf, len%SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
					}

				}
				else
				{
					//直接填0
					wfile.Seek(llSeekAddr, CFile64::begin, 1);
				}


			}

			memcpy(&readLenth, &buffersInput[2], 4);
			ret = epBulkIn->XferData(buffersInput, readLenth);
			if (ret != true)
			{
				CloseHandle(ovLapStatus.hEvent);
				epBulkCmdIn->Abort();
				epBulkOut->Abort();
				epBulkIn->Abort();
				//取消映射
				if (rfile.IsOpen()) rfile.Close();
				if (wfile.IsOpen()) wfile.Close();
				pThis->pFormView3->RichEditShow(nThIdx, L"USB data in transfer err", COLOR_RED, 0, 0);
				//关闭文件映射对象
				pThis->m_pThreadUsbData[nThIdx] = NULL;
				return -1;
			}
			wfile.Write(buffersInput, readLenth);
			nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(buffersInput, readLenth);
			nBufferIdxRd[cwCurBufIdx] = 1;
			len = wfile.GetPosition();
		}
		//正常结束和CANCEL
		else if (buffersInput[0] == 'C')
		{
			if (0 == buffersInput[2])
			{
				//正常退出

				if (0 == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
				{
					//socket号都不对
					pThis->m_nIsAuto[nThIdx] = 0;
					cStatus = PROC_SOCKETALLERR;
				}
				//读追加文件末尾填充
				if (cBufIdx & 0x80)
				{
					if (wfile.IsOpen())
					{
						len = wfile.GetPosition();
						sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f], "%x", &nBufDfLen);
						//要追加填充
						if (nBufDfLen > len)
						{
							//如果要填充1
							if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cBufIdx & 0x7f], "0"))
							{
								len = nBufDfLen - len;
								memset(pSendbuf, 0xff, SIZE16MB);
								for (i = 0; i < len / SIZE16MB; i++)
								{
									wfile.Write(pSendbuf, SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
								}

								if (len%SIZE16MB)
								{
									wfile.Write(pSendbuf, len%SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
								}

							}
							else
							{
								//直接填0
								wfile.Seek(nBufDfLen, CFile64::begin, 1);
							}

						}
					}
					
				}

				//if (cBufIdx & 0x80)
				{
					for (i = 0; i < BUFNUM; i++)
					{
						if (nBufferIdxRd[i])
						{
							CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);

							strtmp.Format(L"%s Checksum=0x%08x", wsztemp, nCheckSums[i]);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
							if (g_nIsEmmc)pThis->pFormView2->DispChecksumInListCtrl(pThis->m_cComboBufSelMap[i], nCheckSums[i], nCheckSums[i]);
						}
					}

				}


				goto PCEND;
			}
			//
			else if (1 == buffersInput[2])
			{
				//cancel
				//	strtmp.Format(L"Cancel thread %s\n", __FUNCTIONW__);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 0, pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit);
				pCProgress->SetPos(0);
				//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				cStatus = PROC_CANCEL;
				pThis->m_nIsAuto[nThIdx] = 0;
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				//pThis->Beep(nThIdx, 0);
				goto PCCANCEL;

			}
			//算法FAIL上报
			else if (2 == buffersInput[2])
			{
				//cancel
				strtmp.Format(L"Fail\n");
				pCProgress->SetPos(0);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				cStatus = PROC_END;
				//	pThis->m_nIsAuto[nThIdx] = 0;
				goto PCEND;

			}

		}
		//DEBUGSTRING
		else if (buffersInput[0] == 'D')
		{
			if (0xff == ((UCHAR)buffersInput[2]))
			{
				int nColor = (buffersInput[3] << 16) | (buffersInput[4] << 8) | (buffersInput[5]);
				CharToTchar(wsztemp, (const char*)(buffersInput + 2 + 4));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, nColor, 0, 0);
			}
			else
			{
				CharToTchar(wsztemp, (const char*)(buffersInput + 2));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
			}


		}
		//进度条 PROGRESS
		else if (buffersInput[0] == 'P')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			pCProgress->SetPos(nScale);
			g_SerialResBuf[SERSOCKBASE + nSocketMax* 32 + (pThis->m_nSiteNo[nThIdx] - 1)] = nScale;

		}
		else if (buffersInput[0] == 'X')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			memcpy(g_ConfigData.nData, &buffersInput[2], 498);

		}
		//BufferSeek
		else if (buffersInput[0] == 'S')
		{

			memcpy(&nSeekL, &buffersInput[2], 4);
			memcpy(&wBufIdx8_Haddr8, &buffersInput[2 + 4], 2);
			llSeekAddr = (UINT64)(wBufIdx8_Haddr8 &0XFF)<< 32| nSeekL;
			cBufIdx = wBufIdx8_Haddr8 >> 8;

			//获得SN
			if ((cBufIdx & 0x7f) == BUFNUM)
			{

			}
			//写操作的BUFFER NUM与大于MAX
			else if (((cBufIdx & 0x7f) > BUFNUM) && ((cBufIdx & 0x80) == 0))
			{
				strtmp.Format(L"Buffer Idx>%d error\n", BUFNUM);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				pThis->Beep(nThIdx, 2);
				goto PCCANCEL;
			}

			//写操作时DEVICE没有这个BUFFER NUMBER
			else if (((cBufIdx & 0x80) == 0) && ((0 == strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[cBufIdx & 0x7f])) || (0 == strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f]))))
			{
				strtmp.Format(L"Buffer Idx %d Invalid\n", cBufIdx);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				goto PCCANCEL;
			}
			else if ((0 == (cBufIdx & 0x80)) && ((cBufIdx & 0X7F) == crCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是写操作

				rfile.Seek(llSeekAddr, CFile64::begin, 1);

			}
			else if ((cBufIdx & 0x80) && ((cBufIdx & 0X7F) == cwCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是读，啥也不干
			}
			//不同要重新打开文件
			else
			{
				//	if (Curfile.IsOpen())
				{
					//无论是否打开，当前读BUFFER idx都要更新
					cwCurBufIdx = cBufIdx & 0X7F;
					//读操作
					if (cBufIdx & 0x80)
					{
						if (wfile.IsOpen())
						{
							wfile.Close();
							strtmp.Format(L"wBuf%d closed", cwCurBufIdx);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
							
							//读直接用路径，不是BUFX
							path = pThis->m_strReadFileDefaultPath[cBufIdx & 0x7f];
							if (rfile.IsOpen())
							{
								if (rfile.GetFileName() == pThis->m_strReadFileDefaultPath[cwCurBufIdx])
								{
									rfile.Close();
								}
							}
							if (!wfile.Open(path, GENERIC_WRITE, 0, OPEN_ALWAYS, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								return 0;
							}
							strtmp.Format(L"buf%d open,seek %d\n", cwCurBufIdx, llSeekAddr);
						}

					}
					//写操作
					else
					{
						if (rfile.IsOpen())
						{
							rfile.Close();
							//strtmp.Format(L"wBuf%d closed", crCurBufIdx);
							//pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
						}
							crCurBufIdx = cBufIdx & 0X7F;
							CharToTchar(wszPath, pstuDevInfo[g_curDeviceSel].szBufNameArrs[crCurBufIdx]);
							path.Format(L"%slib\\%s", g_wszCurPath, wszPath);
							path += L".bf";
							if (wfile.IsOpen())
							{
								if (wfile.GetFileName() == path)
								{
									wfile.Close();
								}
							}
							if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								return 0;
							}
							rfile.Seek(llSeekAddr, CFile64::begin, 1);
							strtmp.Format(L"buf%d open,seek %d\n", crCurBufIdx, llSeekAddr);
						
					}


					//读的话，需要在读到数据的时候填充，不要直接SEEK，

				//	if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);

				}
			}

		}
		//LED状态显示颜色
		else if (buffersInput[0] == 'W')
		{
			memcpy(&nWarnLed, &buffersInput[2], 4);
			//pCProgress->SetPos(nScale);
			wColoridx = nWarnLed >> 16;
			//低16位是掩码

			if (WARNCOLOR_RED == wColoridx)
			{
				//有错误才显示红灯
				for (i = 0; i < nSocketMax; i++)
				{
					if (nWarnLed&(1 << i))
					{
						//重复SOCKET只显示一次
						if (0 == (wErrMaskinoneproc&(1 << i)))
						{
							if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
							{

								strtmp.Format(L"socket%d Failure", i + 1);
								if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 2);
							}

						}

					}
				}
				wErrMaskinoneproc |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_BLUE == wColoridx)
			{
				nNoticeBlue |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticeBlue&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_PURPLE == wColoridx)
			{
				nNoticePurple |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticePurple&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}

			else
			{
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nWarnLed&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}


		}

		if (ret != true)
		{
			pThis->stu_UsbDeviceArr[nThIdx].status = USBNOTCONNECT;

			//SOCKET设置未连接
			g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = USBNOTCONNECT;
			memset(&g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax], SER_SOCKET_DISABLE, nSocketMax);
			memset(&pThis->stu_AutoSeq[nThIdx], 0, sizeof(pThis->stu_AutoSeq[nThIdx]));
			cStatus = PROC_ERRSTOP;
			goto USBERR;

		}

	}

PCEND:
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	//如果选了叠料
	if (pThis->stu_overlap.nIsOverLapCheck[nThIdx])
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Checking", COLOR_YELLOW, 0, 0);
		wErrMaskinoneproc = (~(wErrMaskinoneproc))&(pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
		pThis->stu_overlap.nOverLapSockFail[nThIdx] = wErrMaskinoneproc;

		pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, pThis->stu_overlap.nOverLapSockFail[nThIdx]);
		//如果校验成功，代表叠料了

		if (pThis->stu_overlap.nOverLapSockFail[nThIdx])
		{
			if (pThis->stu_overlap.nOverLapSockFail[nThIdx] == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Check Fail", COLOR_RED, 0, 0);

			}
			for (i = 0; i < SOCKETMAX; i++)
			{
				if ((1 << i)&(pThis->stu_overlap.nOverLapSockFail[nThIdx]))
				{
					strtmp.Format(L"Sok %d overlap Fail", i + 1);
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				}
			}

		}

	}

	//如果选了空检查出错擦除，第一步是空检查，都OK的情况下，直接跳过下面的ERASE
	else if ((pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'b') && (g_nEraseWhenNOTBlank))
	{
		if (wErrMaskinoneproc == 0)
		{
			pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;
		}
		//g_nEraseWhenNOTBlank==1在BLANK中ERRMASK不能设置1，否则会导致后面退出
		wErrMaskinoneproc = 0;

	}

	//全错，又不是blank且g_nEraseWhenNOTBlank=0，则停止
	if (wErrMaskinoneproc == pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)
	{
		pThis->m_nIsAuto[nThIdx] = 0;
	}
PCCANCEL:
	pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus |= (wErrMaskinoneproc | pThis->stu_overlap.nOverLapSockFail[nThIdx]);

	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
USBERR:
	CloseHandle(ovLapStatus.hEvent);
	epBulkCmdIn->Abort();
	epBulkOut->Abort();
	//CloseHandle(OutOvLap.hEvent);
	//取消映射
	if (rfile.IsOpen())
		rfile.Close();
	if (wfile.IsOpen())
	{
		wfile.Close();
	}


	//关闭文件映射对象

	pThis->m_pThreadUsbData[nThIdx] = NULL;

	if (cStatus == PROC_CANCEL)
	{
		strtmp.Empty();
	}
	//如果SOCKET全部报错。就不报下面这些FINISHED了
	if (cStatus != PROC_SOCKETALLERR)
	{
		if (cStatus == PROC_CANCEL)strtmp += L" Canceled";
		else
		{
			if (0 == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" SUCCESS";;
			}
			else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" FAIL";
			}
			else
				strtmp += L" FINISHED";
		}
		if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 6);
		TimeEnd = CTime::GetCurrentTime();
		Timedif = TimeEnd - TimeBegin;
		delay = Timedif.GetMinutes() * 60 + Timedif.GetSeconds();
		strtmp.Format(L"%d seconds", delay);
		pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
	}

	if ((cStatus == PROC_END) || (cStatus == PROC_CANCEL))
	{
		//AUTO中
		if (pThis->m_nIsAuto[nThIdx])
		{
			//叠料检测那次不++；
			if (pThis->stu_overlap.nIsOverLapCheck[nThIdx] == 0)
			{
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;

			}
			else pThis->stu_overlap.nIsOverLapCheck[nThIdx] = 0;


		PRESSURElOOP:


			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx < pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				//中途掉线就不AUTO哦了
				if (pThis->stu_UsbDeviceArr[nThIdx].status != USBNOTCONNECT)
					AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap7, (LPVOID)pThis);
			}
			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
			}
		}
		//单次或者AUTO最后一次
		if (pThis->m_nIsAuto[nThIdx] == 0)
		{
			//记录本次失败的SOCKET
			pThis->m_FailSktLastAuto[nThIdx] = wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
			if (pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;

				if (0xff == (pThis->m_nBtnIdx & 0xff))
				{//确保是AUTO
					if (0 == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO SUCCESS";
					}
					else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO FAIL";
					}
					else
						strtmp = L"AUTO FINISHED";
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
				}
			}
			//统计
			for (i = 0; i < nSocketMax; i++)
			{
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{

					if ((wErrMaskinoneproc | pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus)&(1 << i))
					{

						pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[i]++;
						pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt++;
					}
					pThis->stu_UsbDeviceArr[nThIdx].nSokTotalCnt[i]++;
					pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt++;
				}
			}
			strtmp.Format(L"Total:%d  Success:%d  Fail:%d", pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt - pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 40);
			strtmp.Format(L"SockFail %d,%d,%d,%d,%d,%d,%d,%d", pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[0], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[1], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[2], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[3], \
				pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[4], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[5], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[6], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[7]);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 0);
			pThis->SummaryLog(nThIdx);
			//根据nSockProgStatus ,失败的写回SN 文件
			//if (nNeedDelKey)
			{
				for (nSnChnIdx = 0; nSnChnIdx < pThis->stu_GenSetting.nCnt; nSnChnIdx++)
				{
					if (pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum > 0)
					{
						idx = 0;
						pThis->m_CriticalSectionLog.Lock();
						for (i = 0; i < SOCKETMAX; i++)
						{
							//SOCKET不为空
							if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit&(1 << i))
							{
								//失败，SN码一一写回
								//失败，从KEYPSD文件夹MOVEBACK
								//char path_buffer[_MAX_PATH];
								TCHAR drive[_MAX_DRIVE];
								TCHAR dir[_MAX_DIR];
								TCHAR fname[_MAX_FNAME];
								TCHAR ext[_MAX_EXT];
								_wsplitpath(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], drive, dir, fname, ext);
								if (pThis->stu_GenSetting.nIsDelete)
								{
									strtmp = g_wszCurPath;
								}
								else
								{
									strtmp = drive;
									strtmp += dir;
								}
								strtmp += L"KPsd\\";
								strtmp += fname;
								strtmp += ext;
								if (0 != (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i)))
								{
#if 0
									if (0 != wcslen(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx]))
									{


										if (0 == MoveFile(strtmp, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx]))
										{
											strtmp.Format(L"Skt%d,", i + 1);
											strtmp += fname;
											strtmp += L" move back fail";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

										}
										else
										{
											strtmp.Format(L"Skt%d,", i + 1);
											strtmp += fname;
											strtmp += L" move backed";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
										}
										//SnFile.Open(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], CFile::modeCreate | CFile::modeWrite);
										//SnFile.Write(&pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr[idx*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx]], pThis->stu_GenSetting.nUserSnLen[nSnChnIdx]);
										//SnFile.Close();

									}

									else
									{
										/*AfxMessageBox(L"SN Number empty");
										pThis->m_CriticalSectionSnRd.Unlock();
										break;*/
									}
#endif
								}
								else
								{

									DeleteFile(strtmp);
									if (0 == MoveFile(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], strtmp))
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										strtmp += L" move fail";
										pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

									}
									else
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										if (wcslen(fname))
										{

											strtmp += L" moved";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
											if (pThis->stu_GenSetting.nIsDelete)
											{
												strtmp = g_wszCurPath;
											}
											else
											{
												strtmp = drive;
												strtmp += dir;
											}

											strtmp += L"KPsd\\";

											pThis->logPsdKey4(strtmp, fname);

										}
									}

								}
								idx++;

							}
						}
						pThis->m_CriticalSectionLog.Unlock();
					}

				}
			}

			if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				//全错 FAIL


				pThis->Beep(nThIdx, 2);


			}
			//成功，无错
			else if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->Beep(nThIdx, 0);
			}
			//计算时间
			if (cStatus != PROC_SOCKETALLERR)
			{
				pThis->m_TimeEnd[nThIdx] = CTime::GetCurrentTime();
				Timedif = pThis->m_TimeEnd[nThIdx] - pThis->m_TimeBegin[nThIdx];
				delay = Timedif.GetTotalSeconds();
				strtmp.Format(L"Total %d seconds", delay);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
				pThis->pFormView3->RichEditShow(nThIdx, L"", OPERATIONCOLOR, 0, 0);
			}

			//删除KEY的记录
			for (i = 0; i < 10; i++)
			{
				pThis->stu_UserSNProg[nThIdx][i].nSnNum = 0;
				memset(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile, 0, sizeof(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile));
			}
			pThis->HighZ_CloseV(nThIdx);
		}
	}
	if (pThis->m_nIsAuto[nThIdx] == 0)
	{
		//串口 和网络
		if ((stu_RemoteStat.nRemoteStat > 0) && ((TRUE == stu_RemoteStat.isComOpened) || (pThis->m_SocketObject.IsOpen())))
		{

			

			for (i = 0; i < nSocketMax; i++)
			{
				//使能的SOCKET都RUN
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{
					//失败的
					if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i))
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
					//成功的
					else
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_OK;
					}

				}

				//未使能的，如果是SOCKET ERR=1，是座子号不对
				else
				{
				//	if (pThis->stu_UsbDeviceArr[nThIdx].cSokEncRet[i])
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
				}

			}
			g_SerialResBuf[(pThis->m_nSiteNo[nThIdx] - 1)] = SER_PROG_READY;


		}
		pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus = 0;
	}



	pThis->pFormView1->CntDisplayEachLeftListCtrl(nThIdx, 0);
	//pThis->pFormView2->CntDisplayEachPanel(nThIdx);


	//压力测试
	//如果选择PINCHECK AUTO，使用压力测试的流程，把次数固定
	if (pThis->nAutoSenseAutoRun)
	{
		if (pThis->nAutoSenseAutoRunStartEnd % 2)
		{
			pThis->m_nAutoCntPressure[nThIdx] = 5;
		}
		else
		{
			pThis->m_nAutoCntPressure[nThIdx] = 0;
			pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
			pThis->nAutoSenseAutoRunStartEnd = 0;
			pThis->m_pThreadUsbData[nThIdx] = NULL;

		}

	}
	if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
	{
		if (pThis->m_nAutoCntPressure[nThIdx] > 0)
		{
			nSocketMax = 0;
			pThis->m_nAutoCntPressure[nThIdx]--;
			if (pThis->m_nAutoCntPressure[nThIdx] > 0)
			{
				pThis->m_nIsAuto[nThIdx] = 0xff;
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx = 0;

				goto PRESSURElOOP;
			}
		}
	}
	return 0;
}
UCHAR gSendbuf8[16 * 1024 * 1024];
UCHAR gReadbuf8[4 * 1024 * 1024];
//四个MAP不同之处
//pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread0, (LPVOID)pThis);
//AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap0, (LPVOID)pThis);
//PRESSURElOOP
//PCEND
//PCCANCEL
//USBERR
DWORD WINAPIV CMainFrame::UsbDataProcFileMap8(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR *pSendbuf = gSendbuf8;
	UCHAR *pReadbuf = gReadbuf8;
	CProgressCtrl *pCProgress = &pThis->pFormView2->m_progress8;
	UINT nSnOfset;

	CTimeSpan Timedif;
	int delay;
	CTime TimeBegin = CTime::GetCurrentTime();
	CTime TimeEnd;

	int len;
	int nThIdx = 8;
	int nBufDfLen;
	TCHAR wszPath[MAX_PATH];
	int nNeedDelKey = 0;
	TCHAR wsztemp[180];

	BYTE inEpAddress = 0x83, outEpAddress = 0x01;
	UCHAR cStatus = PROC_END;
	int base = 0;
	UINT *pInt;
	bool ret = 0;
	CString strtmp, showstr = L"";
	PUCHAR		buffersInput = pReadbuf;
	CCyUSBEndPoint *epBulkOut = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(outEpAddress);
	CCyUSBEndPoint *epBulkIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(0X81);
	CCyUSBEndPoint *epBulkCmdIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(inEpAddress);
	long writelenth = 0;
	long nWarnLed = 0;
	long nScale = 0;
	UCHAR *pcData;
	UINT checksum = 0;
	UINT nCheckSums[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	UINT nBufferIdxRd[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
	long readLenth = 1024 * 1024;
	short wColoridx;
	int wErrMaskinoneproc = 0;
	int nNoticeBlue = 0;
	int nNoticePurple = 0;
	UINT64 llSeekAddr = 0;
	//最高位是1表示是读的BUF.
	UCHAR cBufIdx = 0;
	UCHAR  crCurBufIdx = 0;
	UCHAR  cwCurBufIdx = 0;
	UINT nSeekL = 0;
	USHORT wBufIdx8_Haddr8 = 0;
	if (epBulkOut == NULL || epBulkCmdIn == NULL || epBulkIn == NULL) return 1;
	int i, idx = 0;
	int nSocketSenseMask = 0;
	INT nSocketMax = SOCKETMAX;
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		nSocketMax = 2 * SOCKETMAX;
	
	for (i = 0; i < nSocketMax; i++)
	{
		//使能的SOCKET都RUN
		if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_RUN;
		}
		else
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_DISABLE;
		}

	}

	g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = SER_PROG_RUNNING;


	int nBtnIdx;
	Sleep(THDLY);
	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_RUN;


	if (0 == pThis->nAutoSenseAutoRun)
	{
		//没选autosense
	//单步或者AUTO 第一步,才需要下载算法。FPGA等。AUTO的后面几步就不需要了//叠料//非空擦除第一次擦除
		if ((pThis->m_nIsAuto[nThIdx] == 0) || ((pThis->m_nIsAuto[nThIdx]) && (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0)) || pThis->stu_overlap.nIsOverLapCheck[nThIdx] ||
			(g_nEraseWhenNOTBlank && ('e' == pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]])))
		{
			ret = pThis->DownloadConfig_GetPincheck(nThIdx);
		}
	}

	else
	{
		//选了AUTOsense，第一次要DownloadConfig_GetPincheck0，之后每个AUTO的第一次只要要SendConfiWord就行
		if ((pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0) || (0 == pThis->nAutoLoopFirst[nThIdx]))
		{
			pThis->pFormView3->RichEditShow(nThIdx, L"Please insert new chips.....", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 20);
			while (1)
			{

				if (0 == pThis->nAutoLoopFirst[nThIdx])
				{
					ret = pThis->DownloadConfig_GetPincheck(nThIdx);
					if (ret)break;

				}
				else
				{
					ret = pThis->SendConfiWord(nThIdx, 3, pThis->m_cDownData[nThIdx], sizeof(pThis->m_cDownData[nThIdx]));
					if (ret)break;
				}
				pThis->PinSenseInAuto(nThIdx, pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
				pThis->pFormView2->SenseBlink(nThIdx);
				for (i = 0; i < SOCKETMAX; i++)
				{
					if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit & (1 << i))
					{
						//第一次接触上就行
						if (pThis->nAutoLoopFirst[nThIdx])
						{
							if (BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}
						else
						{
							//之后要有状态便话，有先取再放的过程
							if ((BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]) || (BLINK_NULL == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]))
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}

					}
				}
				pThis->nAutoLoopFirst[nThIdx] = 1;
				if (nSocketSenseMask == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)break;
				//停止
				if (0 == (pThis->nAutoSenseAutoRunStartEnd % 2))
				{

					memset(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx]));
					//	memset(stu_PinCheckBlink.nStartBlinkArr[i], 0, sizeof(stu_PinCheckBlink.nStartBlinkArr[i]));
					memset(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx]));
					pThis->m_nAutoCntPressure[nThIdx] = 0;
					pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
					pThis->m_pThreadUsbData[nThIdx] = NULL;
					pThis->nAutoSenseAutoRunStartEnd = 0;
					pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
					for (i = 0; i < SOCKETMAX; i++)
					{
						if (BLINK_START == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
						{
							pThis->pFormView2->mp_Static_ModArr[nThIdx][i]->SetIcon(pThis->pFormView2->stu_PinCheckBlink.HiconsavedIcon[nThIdx][i]);
						}
					}
					return 0;

				}
			}
		}
	}
	if (ret)
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		return 0;
	}
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	strtmp += L" BEGIN...";
	pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 30);

	//OVERLAPPED		OutOvLap;
	//UCHAR *outContext;
	//延续上次的错误状态码
	wErrMaskinoneproc |= pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus;
	//传输数据是否512字节的倍数，要处理，否则，传输死机
	char cIs512Multy = 0;



	CString path;
	CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[0]);
	path.Format(L"%slib\\%s", g_wszCurPath, wsztemp);
	path += L".bf";
	//创建文件对象
	CFileException e;
	CFile64 wfile;
	CFile64 rfile;
	int nSnChnIdx = 0;
	CFile SnFile;

	//如果是读.开读的文件
	if (pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'r')
	{
		if (!wfile.Open(pThis->m_strReadFileDefaultPath[0], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

			return 0;
		}
	}


	strtmp = path;
	showstr = pThis->m_strReadFileDefaultPath[0];
	//if (strtmp.MakeUpper() != showstr.MakeUpper())
	{
		if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
			return 0;
		}
	}
	strtmp.Empty();
	showstr.Empty();


	//要注意的是,必须先操作完 pBuffer才能UnmapViewOfFile,
	//如果先UnmapViewOfFile,再操作 pBuffer则会出错,因为pBuffer已经被释放了
	pInt = (UINT*)pSendbuf;
	pcData = (UCHAR *)pSendbuf;

	epBulkOut->Abort();
	epBulkOut->Reset();
	epBulkCmdIn->Abort();
	epBulkCmdIn->Reset();
	epBulkIn->Abort();
	epBulkIn->Reset();

	//strtmp.Format(L"checksum=%u\n", checksum);
	pCProgress->SetRange(0, 100);
	epBulkOut->TimeOut = INFINITE;
	epBulkCmdIn->TimeOut = INFINITE;
	checksum = 0;


	//面板LED显示

	if (pThis->m_pThreadUserProc1[nThIdx] != NULL)
	{
		strtmp.Format(L"site%d thread proc ptr NOT NULL", pThis->m_nSiteNo[nThIdx]);
		AfxMessageBox(strtmp);
	}
	OVERLAPPED ovLapStatus;
	memset(&ovLapStatus, 0, sizeof(OVERLAPPED));
	ovLapStatus.hEvent = CreateEvent(NULL, false, false, NULL);
	int nMutex = 0;
	while (1)
	{
	
	
	 
	   

	    
		
		PUCHAR context = epBulkCmdIn->BeginDataXfer(buffersInput, readLenth, &ovLapStatus);
		if (nMutex == 0)
		{
			nMutex = 1;
			pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread, (LPVOID)&nThIdx);
		}
		
		bool   wResult = epBulkCmdIn->WaitForXfer(&ovLapStatus,INFINITE);
		bool   fResult = epBulkCmdIn->FinishDataXfer(buffersInput, readLenth, &ovLapStatus, context);

	    
		 ret =wResult && fResult;
		 if (ret != true)
		 {
			 CloseHandle(ovLapStatus.hEvent);
			 epBulkCmdIn->Abort();
			 epBulkOut->Abort();
			 //取消映射
			 if (rfile.IsOpen()) rfile.Close();
			 if (wfile.IsOpen()) wfile.Close();
			 pThis->pFormView3->RichEditShow(nThIdx, L"USB data req transfer err", COLOR_RED, 0, 0);
			 //关闭文件映射对象
			 pThis->m_pThreadUsbData[nThIdx] = NULL;
			 return -1;
		 }
		//OUT数据，主要流程，烧录校验
		if (buffersInput[0] == 'O')
		{
			cIs512Multy = buffersInput[1] & 4;
			memcpy(&writelenth, &buffersInput[2], 4);
			//0,1:SINGLE 和双BUFFER的STARTSTORE
			if ((buffersInput[1] & 3) <= 1)
			{
				if (cIs512Multy)
				{
					len = rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}

				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}

				//SN
				if ((cBufIdx & 0x7f) == BUFNUM)
				{
					pThis->m_CriticalSectionKey.Lock();

					//[0:3]第几组序列,低4位，,其余是OFFSET
					//[4]删除KEY文件吗
					//[5:31]OFFSET
					nSnChnIdx = llSeekAddr & 0xf;
					nNeedDelKey = ((llSeekAddr >> 4) & 1);
					nSnOfset = llSeekAddr >> 5;
					//取得几个序列号
					if (pThis->stu_GenSetting.nUserSnLen[nSnChnIdx])
					{
						int nSnCnt = writelenth / pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						writelenth = nSnCnt*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						if (writelenth > SIZE16MB - 1)
						{
							writelenth = SIZE2MB - 1;
							pThis->pFormView3->RichEditShow(nThIdx, L"change to 2MB(Key must <2MB)", COLOR_RED, 0, 0);
						}
						pThis->GetOneUserSn(nThIdx, nSnChnIdx, nSnOfset, nNeedDelKey, nSnCnt);
						pcData[0] = pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum;
						memcpy(pcData + 1, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr, writelenth);
						writelenth += 1;
					}
					else
					{
						writelenth = 2;
						memset(pcData, 0, writelenth);
					}

					pThis->m_CriticalSectionKey.Unlock();
				}
				//等待三秒

				epBulkOut->XferData(pcData, writelenth);



			}

#if 1

			//下一次准备
			//memset(pcData, 1, 1024);
			//双buffer

			if ((buffersInput[1] & 2))
			{
				if (cIs512Multy)
				{
					len = rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}



				epBulkOut->XferData(pcData, writelenth);


			}
			//
#endif

		}
		//IN数据，读
		else if (buffersInput[0] == 'I')
		{
			if (wfile.IsClosed())
			{
				if (!wfile.Open(pThis->m_strReadFileDefaultPath[cwCurBufIdx], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
				{
					strtmp.Format(L"Failed to open the file %s\n", e.m_strFileName);
					AfxMessageBox(strtmp);
					epBulkCmdIn->Abort();
					epBulkOut->Abort();

					pThis->m_pThreadUsbData[nThIdx] = NULL;
					return 0;
				}
			}
			if (g_nIsEmmc){pThis->m_nIsLoadBufferDll = 1;pThis->m_nIsReadFitnessNeedDataAnalysis=1;}
			cBufIdx |= 0x80;
			len = wfile.GetPosition();
			//把读之前SEEK的位置加上去
			if (llSeekAddr > len)
			{
				//如果要填充1
				if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cwCurBufIdx & 0x7f], "0"))
				{
					memset(pSendbuf, 0xff, SIZE16MB);
					len = llSeekAddr - len;
					for (i = 0; i < len / SIZE16MB; i++)
					{
						wfile.Write(pSendbuf, SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
					}

					if (len%SIZE16MB)
					{
						wfile.Write(pSendbuf, len%SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
					}

				}
				else
				{
					//直接填0
					wfile.Seek(llSeekAddr, CFile64::begin, 1);
				}


			}

			memcpy(&readLenth, &buffersInput[2], 4);
			ret = epBulkIn->XferData(buffersInput, readLenth);
			if (ret != true)
			{
				CloseHandle(ovLapStatus.hEvent);
				epBulkCmdIn->Abort();
				epBulkOut->Abort();
				epBulkIn->Abort();
				//取消映射
				if (rfile.IsOpen()) rfile.Close();
				if (wfile.IsOpen()) wfile.Close();
				pThis->pFormView3->RichEditShow(nThIdx, L"USB data in transfer err", COLOR_RED, 0, 0);
				//关闭文件映射对象
				pThis->m_pThreadUsbData[nThIdx] = NULL;
				return -1;
			}
			wfile.Write(buffersInput, readLenth);
			nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(buffersInput, readLenth);
			nBufferIdxRd[cwCurBufIdx] = 1;
			len = wfile.GetPosition();
		}
		//正常结束和CANCEL
		else if (buffersInput[0] == 'C')
		{
			if (0 == buffersInput[2])
			{
				//正常退出

				if (0 == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
				{
					//socket号都不对
					pThis->m_nIsAuto[nThIdx] = 0;
					cStatus = PROC_SOCKETALLERR;
				}
				//读追加文件末尾填充
				if (cBufIdx & 0x80)
				{
					if (wfile.IsOpen())
					{
						len = wfile.GetPosition();
						sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f], "%x", &nBufDfLen);
						//要追加填充
						if (nBufDfLen > len)
						{
							//如果要填充1
							if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cBufIdx & 0x7f], "0"))
							{
								len = nBufDfLen - len;
								memset(pSendbuf, 0xff, SIZE16MB);
								for (i = 0; i < len / SIZE16MB; i++)
								{
									wfile.Write(pSendbuf, SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
								}

								if (len%SIZE16MB)
								{
									wfile.Write(pSendbuf, len%SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
								}

							}
							else
							{
								//直接填0
								wfile.Seek(nBufDfLen, CFile64::begin, 1);
							}

						}
					}
					
				}

				//if (cBufIdx & 0x80)
				{
					for (i = 0; i < BUFNUM; i++)
					{
						if (nBufferIdxRd[i])
						{
							CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);

							strtmp.Format(L"%s Checksum=0x%08x", wsztemp, nCheckSums[i]);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
							if (g_nIsEmmc)pThis->pFormView2->DispChecksumInListCtrl(pThis->m_cComboBufSelMap[i], nCheckSums[i], nCheckSums[i]);
						}
					}

				}


				goto PCEND;
			}
			//
			else if (1 == buffersInput[2])
			{
				//cancel
				//	strtmp.Format(L"Cancel thread %s\n", __FUNCTIONW__);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 0, pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit);
				pCProgress->SetPos(0);
				//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				cStatus = PROC_CANCEL;
				pThis->m_nIsAuto[nThIdx] = 0;
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				//pThis->Beep(nThIdx, 0);
				goto PCCANCEL;

			}
			//算法FAIL上报
			else if (2 == buffersInput[2])
			{
				//cancel
				strtmp.Format(L"Fail\n");
				pCProgress->SetPos(0);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				cStatus = PROC_END;
				//	pThis->m_nIsAuto[nThIdx] = 0;
				goto PCEND;

			}

		}
		//DEBUGSTRING
		else if (buffersInput[0] == 'D')
		{
			if (0xff == ((UCHAR)buffersInput[2]))
			{
				int nColor = (buffersInput[3] << 16) | (buffersInput[4] << 8) | (buffersInput[5]);
				CharToTchar(wsztemp, (const char*)(buffersInput + 2 + 4));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, nColor, 0, 0);
			}
			else
			{
				CharToTchar(wsztemp, (const char*)(buffersInput + 2));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
			}


		}
		//进度条 PROGRESS
		else if (buffersInput[0] == 'P')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			pCProgress->SetPos(nScale);
			g_SerialResBuf[SERSOCKBASE + nSocketMax* 32 + (pThis->m_nSiteNo[nThIdx] - 1)] = nScale;

		}
		else if (buffersInput[0] == 'X')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			memcpy(g_ConfigData.nData, &buffersInput[2], 498);

		}
		//BufferSeek
		else if (buffersInput[0] == 'S')
		{

			memcpy(&nSeekL, &buffersInput[2], 4);
			memcpy(&wBufIdx8_Haddr8, &buffersInput[2 + 4], 2);
			llSeekAddr = (UINT64)(wBufIdx8_Haddr8 &0XFF)<< 32| nSeekL;
			cBufIdx = wBufIdx8_Haddr8 >> 8;

			//获得SN
			if ((cBufIdx & 0x7f) == BUFNUM)
			{

			}
			//写操作的BUFFER NUM与大于MAX
			else if (((cBufIdx & 0x7f) > BUFNUM) && ((cBufIdx & 0x80) == 0))
			{
				strtmp.Format(L"Buffer Idx>%d error\n", BUFNUM);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				pThis->Beep(nThIdx, 2);
				goto PCCANCEL;
			}

			//写操作时DEVICE没有这个BUFFER NUMBER
			else if (((cBufIdx & 0x80) == 0) && ((0 == strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[cBufIdx & 0x7f])) || (0 == strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f]))))
			{
				strtmp.Format(L"Buffer Idx %d Invalid\n", cBufIdx);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				goto PCCANCEL;
			}
			else if ((0 == (cBufIdx & 0x80)) && ((cBufIdx & 0X7F) == crCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是写操作

				rfile.Seek(llSeekAddr, CFile64::begin, 1);

			}
			else if ((cBufIdx & 0x80) && ((cBufIdx & 0X7F) == cwCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是读，啥也不干
			}
			//不同要重新打开文件
			else
			{
				//	if (Curfile.IsOpen())
				{
					//无论是否打开，当前读BUFFER idx都要更新
					cwCurBufIdx = cBufIdx & 0X7F;
					//读操作
					if (cBufIdx & 0x80)
					{
						if (wfile.IsOpen())
						{
							wfile.Close();
							strtmp.Format(L"wBuf%d closed", cwCurBufIdx);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
							
							//读直接用路径，不是BUFX
							path = pThis->m_strReadFileDefaultPath[cBufIdx & 0x7f];
							if (rfile.IsOpen())
							{
								if (rfile.GetFileName() == pThis->m_strReadFileDefaultPath[cwCurBufIdx])
								{
									rfile.Close();
								}
							}
							if (!wfile.Open(path, GENERIC_WRITE, 0, OPEN_ALWAYS, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								return 0;
							}
							strtmp.Format(L"buf%d open,seek %d\n", cwCurBufIdx, llSeekAddr);
						}

					}
					//写操作
					else
					{
						if (rfile.IsOpen())
						{
							rfile.Close();
							//strtmp.Format(L"wBuf%d closed", crCurBufIdx);
							//pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
						}
							crCurBufIdx = cBufIdx & 0X7F;
							CharToTchar(wszPath, pstuDevInfo[g_curDeviceSel].szBufNameArrs[crCurBufIdx]);
							path.Format(L"%slib\\%s", g_wszCurPath, wszPath);
							path += L".bf";
							if (wfile.IsOpen())
							{
								if (wfile.GetFileName() == path)
								{
									wfile.Close();
								}
							}
							if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								return 0;
							}
							rfile.Seek(llSeekAddr, CFile64::begin, 1);
							strtmp.Format(L"buf%d open,seek %d\n", crCurBufIdx, llSeekAddr);
						
					}


					//读的话，需要在读到数据的时候填充，不要直接SEEK，

					//if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);

				}
			}

		}
		//LED状态显示颜色
		else if (buffersInput[0] == 'W')
		{
			memcpy(&nWarnLed, &buffersInput[2], 4);
			//pCProgress->SetPos(nScale);
			wColoridx = nWarnLed >> 16;
			//低16位是掩码

			if (WARNCOLOR_RED == wColoridx)
			{
				//有错误才显示红灯
				for (i = 0; i < nSocketMax; i++)
				{
					if (nWarnLed&(1 << i))
					{
						//重复SOCKET只显示一次
						if (0 == (wErrMaskinoneproc&(1 << i)))
						{
							if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
							{

								strtmp.Format(L"socket%d Failure", i + 1);
								if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 2);
							}

						}

					}
				}
				wErrMaskinoneproc |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_BLUE == wColoridx)
			{
				nNoticeBlue |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticeBlue&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_PURPLE == wColoridx)
			{
				nNoticePurple |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticePurple&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}

			else
			{
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nWarnLed&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}


		}

		if (ret != true)
		{
			pThis->stu_UsbDeviceArr[nThIdx].status = USBNOTCONNECT;

			//SOCKET设置未连接
			g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = USBNOTCONNECT;
			memset(&g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax], SER_SOCKET_DISABLE, nSocketMax);
			memset(&pThis->stu_AutoSeq[nThIdx], 0, sizeof(pThis->stu_AutoSeq[nThIdx]));
			cStatus = PROC_ERRSTOP;
			goto USBERR;

		}

	}

PCEND:
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	//如果选了叠料
	if (pThis->stu_overlap.nIsOverLapCheck[nThIdx])
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Checking", COLOR_YELLOW, 0, 0);
		wErrMaskinoneproc = (~(wErrMaskinoneproc))&(pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
		pThis->stu_overlap.nOverLapSockFail[nThIdx] = wErrMaskinoneproc;

		pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, pThis->stu_overlap.nOverLapSockFail[nThIdx]);
		//如果校验成功，代表叠料了

		if (pThis->stu_overlap.nOverLapSockFail[nThIdx])
		{
			if (pThis->stu_overlap.nOverLapSockFail[nThIdx] == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Check Fail", COLOR_RED, 0, 0);

			}
			for (i = 0; i < SOCKETMAX; i++)
			{
				if ((1 << i)&(pThis->stu_overlap.nOverLapSockFail[nThIdx]))
				{
					strtmp.Format(L"Sok %d overlap Fail", i + 1);
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				}
			}

		}

	}

	//如果选了空检查出错擦除，第一步是空检查，都OK的情况下，直接跳过下面的ERASE
	else if ((pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'b') && (g_nEraseWhenNOTBlank))
	{
		if (wErrMaskinoneproc == 0)
		{
			pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;
		}
		//g_nEraseWhenNOTBlank==1在BLANK中ERRMASK不能设置1，否则会导致后面退出
		wErrMaskinoneproc = 0;

	}

	//全错，又不是blank且g_nEraseWhenNOTBlank=0，则停止
	if (wErrMaskinoneproc == pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)
	{
		pThis->m_nIsAuto[nThIdx] = 0;
	}
PCCANCEL:
	pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus |= (wErrMaskinoneproc | pThis->stu_overlap.nOverLapSockFail[nThIdx]);

	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
USBERR:
	CloseHandle(ovLapStatus.hEvent);
	epBulkCmdIn->Abort();
	epBulkOut->Abort();
	//CloseHandle(OutOvLap.hEvent);
	//取消映射
	if (rfile.IsOpen())
		rfile.Close();
	if (wfile.IsOpen())
	{
		wfile.Close();
	}


	//关闭文件映射对象

	pThis->m_pThreadUsbData[nThIdx] = NULL;

	if (cStatus == PROC_CANCEL)
	{
		strtmp.Empty();
	}
	//如果SOCKET全部报错。就不报下面这些FINISHED了
	if (cStatus != PROC_SOCKETALLERR)
	{
		if (cStatus == PROC_CANCEL)strtmp += L" Canceled";
		else
		{
			if (0 == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" SUCCESS";;
			}
			else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" FAIL";
			}
			else
				strtmp += L" FINISHED";
		}
		if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 6);
		TimeEnd = CTime::GetCurrentTime();
		Timedif = TimeEnd - TimeBegin;
		delay = Timedif.GetMinutes() * 60 + Timedif.GetSeconds();
		strtmp.Format(L"%d seconds", delay);
		pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
	}

	if ((cStatus == PROC_END) || (cStatus == PROC_CANCEL))
	{
		//AUTO中
		if (pThis->m_nIsAuto[nThIdx])
		{
			//叠料检测那次不++；
			if (pThis->stu_overlap.nIsOverLapCheck[nThIdx] == 0)
			{
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;

			}
			else pThis->stu_overlap.nIsOverLapCheck[nThIdx] = 0;


		PRESSURElOOP:


			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx < pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				//中途掉线就不AUTO哦了
				if (pThis->stu_UsbDeviceArr[nThIdx].status != USBNOTCONNECT)
					AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap8, (LPVOID)pThis);
			}
			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
			}
		}
		//单次或者AUTO最后一次
		if (pThis->m_nIsAuto[nThIdx] == 0)
		{
			//记录本次失败的SOCKET
			pThis->m_FailSktLastAuto[nThIdx] = wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
			if (pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;

				if (0xff == (pThis->m_nBtnIdx & 0xff))
				{//确保是AUTO
					if (0 == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO SUCCESS";
					}
					else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO FAIL";
					}
					else
						strtmp = L"AUTO FINISHED";
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
				}
			}
			//统计
			for (i = 0; i < nSocketMax; i++)
			{
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{

					if ((wErrMaskinoneproc | pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus)&(1 << i))
					{

						pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[i]++;
						pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt++;
					}
					pThis->stu_UsbDeviceArr[nThIdx].nSokTotalCnt[i]++;
					pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt++;
				}
			}
			strtmp.Format(L"Total:%d  Success:%d  Fail:%d", pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt - pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 40);
			strtmp.Format(L"SockFail %d,%d,%d,%d,%d,%d,%d,%d", pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[0], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[1], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[2], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[3], \
				pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[4], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[5], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[6], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[7]);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 0);
			pThis->SummaryLog(nThIdx);
			//根据nSockProgStatus ,失败的写回SN 文件
			//if (nNeedDelKey)
			{
				for (nSnChnIdx = 0; nSnChnIdx < pThis->stu_GenSetting.nCnt; nSnChnIdx++)
				{
					if (pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum > 0)
					{
						idx = 0;
						pThis->m_CriticalSectionLog.Lock();
						for (i = 0; i < SOCKETMAX; i++)
						{
							//SOCKET不为空
							if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit&(1 << i))
							{
								//失败，SN码一一写回
								//失败，从KEYPSD文件夹MOVEBACK
								//char path_buffer[_MAX_PATH];
								TCHAR drive[_MAX_DRIVE];
								TCHAR dir[_MAX_DIR];
								TCHAR fname[_MAX_FNAME];
								TCHAR ext[_MAX_EXT];
								_wsplitpath(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], drive, dir, fname, ext);
								if (pThis->stu_GenSetting.nIsDelete)
								{
									strtmp = g_wszCurPath;
								}
								else
								{
									strtmp = drive;
									strtmp += dir;
								}
								strtmp += L"KPsd\\";
								strtmp += fname;
								strtmp += ext;
								if (0 != (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i)))
								{
#if 0
									if (0 != wcslen(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx]))
									{


										if (0 == MoveFile(strtmp, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx]))
										{
											strtmp.Format(L"Skt%d,", i + 1);
											strtmp += fname;
											strtmp += L" move back fail";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

										}
										else
										{
											strtmp.Format(L"Skt%d,", i + 1);
											strtmp += fname;
											strtmp += L" move backed";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
										}
										//SnFile.Open(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], CFile::modeCreate | CFile::modeWrite);
										//SnFile.Write(&pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr[idx*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx]], pThis->stu_GenSetting.nUserSnLen[nSnChnIdx]);
										//SnFile.Close();

									}

									else
									{
										/*AfxMessageBox(L"SN Number empty");
										pThis->m_CriticalSectionSnRd.Unlock();
										break;*/
									}
#endif
								}
								else
								{

									DeleteFile(strtmp);
									if (0 == MoveFile(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], strtmp))
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										strtmp += L" move fail";
										pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

									}
									else
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										if (wcslen(fname))
										{

											strtmp += L" moved";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
											if (pThis->stu_GenSetting.nIsDelete)
											{
												strtmp = g_wszCurPath;
											}
											else
											{
												strtmp = drive;
												strtmp += dir;
											}

											strtmp += L"KPsd\\";

											pThis->logPsdKey4(strtmp, fname);

										}
									}

								}
								idx++;

							}
						}
						pThis->m_CriticalSectionLog.Unlock();
					}

				}
			}

			if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				//全错 FAIL


				pThis->Beep(nThIdx, 2);


			}
			//成功，无错
			else if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->Beep(nThIdx, 0);
			}
			//计算时间
			if (cStatus != PROC_SOCKETALLERR)
			{
				pThis->m_TimeEnd[nThIdx] = CTime::GetCurrentTime();
				Timedif = pThis->m_TimeEnd[nThIdx] - pThis->m_TimeBegin[nThIdx];
				delay = Timedif.GetTotalSeconds();
				strtmp.Format(L"Total %d seconds", delay);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
				pThis->pFormView3->RichEditShow(nThIdx, L"", OPERATIONCOLOR, 0, 0);
			}

			//删除KEY的记录
			for (i = 0; i < 10; i++)
			{
				pThis->stu_UserSNProg[nThIdx][i].nSnNum = 0;
				memset(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile, 0, sizeof(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile));
			}
			pThis->HighZ_CloseV(nThIdx);
		}
	}
	if (pThis->m_nIsAuto[nThIdx] == 0)
	{
		//串口 和网络
		if ((stu_RemoteStat.nRemoteStat > 0) && ((TRUE == stu_RemoteStat.isComOpened) || (pThis->m_SocketObject.IsOpen())))
		{

			
			for (i = 0; i < nSocketMax; i++)
			{
				//使能的SOCKET都RUN
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{
					//失败的
					if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i))
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
					//成功的
					else
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_OK;
					}

				}

				//未使能的，如果是SOCKET ERR=1，是座子号不对
				else
				{
					//if (pThis->stu_UsbDeviceArr[nThIdx].cSokEncRet[i])
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
				}

			}
			g_SerialResBuf[(pThis->m_nSiteNo[nThIdx] - 1)] = SER_PROG_READY;



		}
		pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus = 0;
	}



	pThis->pFormView1->CntDisplayEachLeftListCtrl(nThIdx, 0);
	//pThis->pFormView2->CntDisplayEachPanel(nThIdx);


	//压力测试
	//如果选择PINCHECK AUTO，使用压力测试的流程，把次数固定
	if (pThis->nAutoSenseAutoRun)
	{
		if (pThis->nAutoSenseAutoRunStartEnd % 2)
		{
			pThis->m_nAutoCntPressure[nThIdx] = 5;
		}
		else
		{
			pThis->m_nAutoCntPressure[nThIdx] = 0;
			pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
			pThis->nAutoSenseAutoRunStartEnd = 0;
			pThis->m_pThreadUsbData[nThIdx] = NULL;

		}

	}
	if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
	{
		if (pThis->m_nAutoCntPressure[nThIdx] > 0)
		{
			nSocketMax = 0;
			pThis->m_nAutoCntPressure[nThIdx]--;
			if (pThis->m_nAutoCntPressure[nThIdx] > 0)
			{
				pThis->m_nIsAuto[nThIdx] = 0xff;
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx = 0;

				goto PRESSURElOOP;
			}
		}
	}
	return 0;
}
UCHAR gSendbuf9[16 * 1024 * 1024];
UCHAR gReadbuf9[4 * 1024 * 1024];
//四个MAP不同之处
//pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread0, (LPVOID)pThis);
//AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap0, (LPVOID)pThis);
//PRESSURElOOP
//PCEND
//PCCANCEL
//USBERR
DWORD WINAPIV CMainFrame::UsbDataProcFileMap9(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR *pSendbuf = gSendbuf9;
	UCHAR *pReadbuf = gReadbuf9;
	CProgressCtrl *pCProgress = &pThis->pFormView2->m_progress9;
	UINT nSnOfset;

	CTimeSpan Timedif;
	int delay;
	CTime TimeBegin = CTime::GetCurrentTime();
	CTime TimeEnd;

	int len;
	int nThIdx = 9;
	int nBufDfLen;
	TCHAR wszPath[MAX_PATH];
	int nNeedDelKey = 0;
	TCHAR wsztemp[180];

	BYTE inEpAddress = 0x83, outEpAddress = 0x01;
	UCHAR cStatus = PROC_END;
	int base = 0;
	UINT *pInt;
	bool ret = 0;
	CString strtmp, showstr = L"";
	PUCHAR		buffersInput = pReadbuf;
	CCyUSBEndPoint *epBulkOut = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(outEpAddress);
	CCyUSBEndPoint *epBulkIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(0X81);
	CCyUSBEndPoint *epBulkCmdIn = pThis->stu_UsbDeviceArr[nThIdx].pUsbDevice->EndPointOf(inEpAddress);
	long writelenth = 0;
	long nWarnLed = 0;
	long nScale = 0;
	UCHAR *pcData;
	UINT checksum = 0;
	UINT nCheckSums[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	UINT nBufferIdxRd[BUFNUM] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
	long readLenth = 1024 * 1024;
	short wColoridx;
	int wErrMaskinoneproc = 0;
	int nNoticeBlue = 0;
	int nNoticePurple = 0;
	UINT64 llSeekAddr = 0;
	//最高位是1表示是读的BUF.
	UCHAR cBufIdx = 0;
	UCHAR  crCurBufIdx = 0;
	UCHAR  cwCurBufIdx = 0;
	UINT nSeekL = 0;
	USHORT wBufIdx8_Haddr8 = 0;
	if (epBulkOut == NULL || epBulkCmdIn == NULL || epBulkIn == NULL) return 1;
	int i, idx = 0;
	int nSocketSenseMask = 0;
	INT nSocketMax = SOCKETMAX;
	if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		nSocketMax = 2 * SOCKETMAX;

	for (i = 0; i < nSocketMax; i++)
	{
		//使能的SOCKET都RUN
		if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_RUN;
		}
		else
		{
			g_SerialResBuf[SERSOCKBASE + nSocketMax*(pThis->m_nSiteNo[nThIdx] - 1) + i] = SER_SOCKET_DISABLE;
		}

	}

	g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = SER_PROG_RUNNING;

int nBtnIdx;
	Sleep(THDLY);
	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_RUN;


	if (0 == pThis->nAutoSenseAutoRun)
	{
		//没选autosense
	//单步或者AUTO 第一步,才需要下载算法。FPGA等。AUTO的后面几步就不需要了//叠料//非空擦除第一次擦除
		if ((pThis->m_nIsAuto[nThIdx] == 0) || ((pThis->m_nIsAuto[nThIdx]) && (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0)) || pThis->stu_overlap.nIsOverLapCheck[nThIdx] ||
			(g_nEraseWhenNOTBlank && ('e' == pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]])))
		{
			ret = pThis->DownloadConfig_GetPincheck(nThIdx);
		}
	}

	else
	{
		//选了AUTOsense，第一次要DownloadConfig_GetPincheck0，之后每个AUTO的第一次只要要SendConfiWord就行
		if ((pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == 0) || (0 == pThis->nAutoLoopFirst[nThIdx]))
		{
			pThis->pFormView3->RichEditShow(nThIdx, L"Please insert new chips.....", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 20);
			while (1)
			{

				if (0 == pThis->nAutoLoopFirst[nThIdx])
				{
					ret = pThis->DownloadConfig_GetPincheck(nThIdx);
					if (ret)break;

				}
				else
				{
					ret = pThis->SendConfiWord(nThIdx, 3, pThis->m_cDownData[nThIdx], sizeof(pThis->m_cDownData[nThIdx]));
					if (ret)break;
				}
				pThis->PinSenseInAuto(nThIdx, pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
				pThis->pFormView2->SenseBlink(nThIdx);
				for (i = 0; i < SOCKETMAX; i++)
				{
					if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit & (1 << i))
					{
						//第一次接触上就行
						if (pThis->nAutoLoopFirst[nThIdx])
						{
							if (BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}
						else
						{
							//之后要有状态便话，有先取再放的过程
							if ((BLINK_END2 == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]) || (BLINK_NULL == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i]))
							{
								nSocketSenseMask |= (1 << i);
								pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i] = 0;
							}
						}

					}
				}
				pThis->nAutoLoopFirst[nThIdx] = 1;
				if (nSocketSenseMask == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)break;
				//停止
				if (0 == (pThis->nAutoSenseAutoRunStartEnd % 2))
				{

					memset(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nEndBlinkArr[nThIdx]));
					//	memset(stu_PinCheckBlink.nStartBlinkArr[i], 0, sizeof(stu_PinCheckBlink.nStartBlinkArr[i]));
					memset(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx], 0, sizeof(pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx]));
					pThis->m_nAutoCntPressure[nThIdx] = 0;
					pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
					pThis->m_pThreadUsbData[nThIdx] = NULL;
					pThis->nAutoSenseAutoRunStartEnd = 0;
					pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
					for (i = 0; i < SOCKETMAX; i++)
					{
						if (BLINK_START == pThis->pFormView2->stu_PinCheckBlink.nStatus[nThIdx][i])
						{
							pThis->pFormView2->mp_Static_ModArr[nThIdx][i]->SetIcon(pThis->pFormView2->stu_PinCheckBlink.HiconsavedIcon[nThIdx][i]);
						}
					}
					return 0;

				}
			}
		}
	}
	if (ret)
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		return 0;
	}
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	strtmp += L" BEGIN...";
	pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 30);

	//OVERLAPPED		OutOvLap;
	//UCHAR *outContext;
	//延续上次的错误状态码
	wErrMaskinoneproc |= pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus;
	//传输数据是否512字节的倍数，要处理，否则，传输死机
	char cIs512Multy = 0;


	CString path;
	CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[0]);
	path.Format(L"%slib\\%s", g_wszCurPath, wsztemp);
	path += L".bf";
	//创建文件对象
	CFileException e;
	CFile64 wfile;
	CFile64 rfile;
	int nSnChnIdx = 0;
	CFile SnFile;

	

	//如果是读.开读的文件
	if (pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'r')
	{
		if (!wfile.Open(pThis->m_strReadFileDefaultPath[0], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

			return 0;
		}
	}
	strtmp = path;
	showstr = pThis->m_strReadFileDefaultPath[0];
	//if (strtmp.MakeUpper() != showstr.MakeUpper())
	{
		if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
		{
			strtmp.Format(L"Failed to open the file %s", e.m_strFileName);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
			return 0;
		}
	}
	strtmp.Empty();
	showstr.Empty();



	//要注意的是,必须先操作完 pBuffer才能UnmapViewOfFile,
	//如果先UnmapViewOfFile,再操作 pBuffer则会出错,因为pBuffer已经被释放了
	pInt = (UINT*)pSendbuf;
	pcData = (UCHAR *)pSendbuf;

	epBulkOut->Abort();
	epBulkOut->Reset();
	epBulkCmdIn->Abort();
	epBulkCmdIn->Reset();
	epBulkIn->Abort();
	epBulkIn->Reset();

	//strtmp.Format(L"checksum=%u\n", checksum);
	pCProgress->SetRange(0, 100);
	epBulkOut->TimeOut = INFINITE;
	epBulkCmdIn->TimeOut = INFINITE;
	checksum = 0;


	//面板LED显示

	if (pThis->m_pThreadUserProc1[nThIdx] != NULL)
	{
		strtmp.Format(L"site%d thread proc ptr NOT NULL", pThis->m_nSiteNo[nThIdx]);
		AfxMessageBox(strtmp);
	}
	OVERLAPPED ovLapStatus;
	memset(&ovLapStatus, 0, sizeof(OVERLAPPED));
	ovLapStatus.hEvent = CreateEvent(NULL, false, false, NULL);
	int nMutex = 0;
	while (1)
	{
	
	
	 
	   

	    
		
		PUCHAR context = epBulkCmdIn->BeginDataXfer(buffersInput, readLenth, &ovLapStatus);
		if (nMutex == 0)
		{
			nMutex = 1;
			pThis->m_pThreadUserProc1[nThIdx] = AfxBeginThread((AFX_THREADPROC)pThis->Downloadthread, (LPVOID)&nThIdx);
		}
		
		bool   wResult = epBulkCmdIn->WaitForXfer(&ovLapStatus,INFINITE);
		bool   fResult = epBulkCmdIn->FinishDataXfer(buffersInput, readLenth, &ovLapStatus, context);

	    
		 ret =wResult && fResult;
		 if (ret != true)
		 {
			 CloseHandle(ovLapStatus.hEvent);
			 epBulkCmdIn->Abort();
			 epBulkOut->Abort();
			 //取消映射
			 if (rfile.IsOpen()) rfile.Close();
			 if (wfile.IsOpen()) wfile.Close();
			 pThis->pFormView3->RichEditShow(nThIdx, L"USB data req transfer err", COLOR_RED, 0, 0);
			 //关闭文件映射对象
			 pThis->m_pThreadUsbData[nThIdx] = NULL;
			 return -1;
		 }
		//OUT数据，主要流程，烧录校验
		if (buffersInput[0] == 'O')
		{
			cIs512Multy = buffersInput[1] & 4;
			memcpy(&writelenth, &buffersInput[2], 4);
			//0,1:SINGLE 和双BUFFER的STARTSTORE
			if ((buffersInput[1] & 3) <= 1)
			{
				if (cIs512Multy)
				{
					len = rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}

				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}

				//SN
				if ((cBufIdx & 0x7f) == BUFNUM)
				{
					pThis->m_CriticalSectionKey.Lock();

					//[0:3]第几组序列,低4位，,其余是OFFSET
					//[4]删除KEY文件吗
					//[5:31]OFFSET
					nSnChnIdx = llSeekAddr & 0xf;
					nNeedDelKey = ((llSeekAddr >> 4) & 1);
					nSnOfset = llSeekAddr >> 5;
					//取得几个序列号
					if (pThis->stu_GenSetting.nUserSnLen[nSnChnIdx])
					{
						int nSnCnt = writelenth / pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						writelenth = nSnCnt*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx];
						if (writelenth > SIZE16MB - 1)
						{
							writelenth = SIZE2MB - 1;
							pThis->pFormView3->RichEditShow(nThIdx, L"change to 2MB(Key must <2MB)", COLOR_RED, 0, 0);
						}
						pThis->GetOneUserSn(nThIdx, nSnChnIdx, nSnOfset, nNeedDelKey, nSnCnt);
						pcData[0] = pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum;
						memcpy(pcData + 1, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr, writelenth);
						writelenth += 1;
					}
					else
					{
						writelenth = 2;
						memset(pcData, 0, writelenth);
					}

					pThis->m_CriticalSectionKey.Unlock();
				}
				//等待三秒

				epBulkOut->XferData(pcData, writelenth);



			}

#if 1

			//下一次准备
			//memset(pcData, 1, 1024);
			//双buffer

			if ((buffersInput[1] & 2))
			{
				if (cIs512Multy)
				{
					len=rfile.Read(pSendbuf, writelenth - 1);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - 1 - len);
					}
				}
				else
				{
					len = rfile.Read(pSendbuf, writelenth);
					if (len < writelenth)
					{
						memset(pSendbuf + len, 0, writelenth - len);
					}
				}



				epBulkOut->XferData(pcData, writelenth);


			}
			//
#endif

		}
		//IN数据，读
		else if (buffersInput[0] == 'I')
		{
			if (wfile.IsClosed())
			{
				if (!wfile.Open(pThis->m_strReadFileDefaultPath[cwCurBufIdx], GENERIC_WRITE, 0, CREATE_ALWAYS, &e))
				{
					strtmp.Format(L"Failed to open the file %s\n", e.m_strFileName);
					AfxMessageBox(strtmp);
					epBulkCmdIn->Abort();
					epBulkOut->Abort();

					pThis->m_pThreadUsbData[nThIdx] = NULL;
					return 0;
				}
			}
			if (g_nIsEmmc){pThis->m_nIsLoadBufferDll = 1;pThis->m_nIsReadFitnessNeedDataAnalysis=1;}
			cBufIdx |= 0x80;
			len = wfile.GetPosition();
			//把读之前SEEK的位置加上去
			if (llSeekAddr > len)
			{
				//如果要填充1
				if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cwCurBufIdx & 0x7f], "0"))
				{
					memset(pSendbuf, 0xff, SIZE16MB);
					len = llSeekAddr - len;
					for (i = 0; i < len / SIZE16MB; i++)
					{
						wfile.Write(pSendbuf, SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
					}

					if (len%SIZE16MB)
					{
						wfile.Write(pSendbuf, len%SIZE16MB);
						nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
					}


				}
				else
				{
					//直接填0
					wfile.Seek(llSeekAddr, CFile64::begin, 1);
				}


			}

			memcpy(&readLenth, &buffersInput[2], 4);
			ret = epBulkIn->XferData(buffersInput, readLenth);
			if (ret != true)
			{
				CloseHandle(ovLapStatus.hEvent);
				epBulkCmdIn->Abort();
				epBulkOut->Abort();
				epBulkIn->Abort();
				//取消映射
				if (rfile.IsOpen()) rfile.Close();
				if (wfile.IsOpen()) wfile.Close();
				pThis->pFormView3->RichEditShow(nThIdx, L"USB data in transfer err", COLOR_RED, 0, 0);
				//关闭文件映射对象
				pThis->m_pThreadUsbData[nThIdx] = NULL;
				return -1;
			}
			wfile.Write(buffersInput, readLenth);
			nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(buffersInput, readLenth);
			nBufferIdxRd[cwCurBufIdx] = 1;
			len = wfile.GetPosition();
		}
		//正常结束和CANCEL
		else if (buffersInput[0] == 'C')
		{
			if (0 == buffersInput[2])
			{
				//正常退出

				if (0 == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
				{
					//socket号都不对
					pThis->m_nIsAuto[nThIdx] = 0;
					cStatus = PROC_SOCKETALLERR;
				}
				//读追加文件末尾填充
				if (cBufIdx & 0x80)
				{
					if (wfile.IsOpen())
					{
						len = wfile.GetPosition();
						sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f], "%x", &nBufDfLen);
						//要追加填充
						if (nBufDfLen > len)
						{
							//如果要填充1
							if (1 == strcmp(pstuDevInfo[g_curDeviceSel].szBufValueArrs[cBufIdx & 0x7f], "0"))
							{
								len = nBufDfLen - len;
								memset(pSendbuf, 0xff, SIZE16MB);
								for (i = 0; i < len / SIZE16MB; i++)
								{
									wfile.Write(pSendbuf, SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, SIZE16MB);
								}

								if (len%SIZE16MB)
								{
									wfile.Write(pSendbuf, len%SIZE16MB);
									nCheckSums[cwCurBufIdx] = checksum += CalcCheckSum(pSendbuf, len%SIZE16MB);
								}

							}
							else
							{
								//直接填0
								wfile.Seek(nBufDfLen, CFile64::begin, 1);
							}

						}
					}
				
				}

				//if (cBufIdx & 0x80)
				{
					for (i = 0; i < BUFNUM; i++)
					{
						if (nBufferIdxRd[i])
						{
							CharToTchar(wsztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);

							strtmp.Format(L"%s Checksum=0x%08x", wsztemp, nCheckSums[i]);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
							if (g_nIsEmmc)pThis->pFormView2->DispChecksumInListCtrl(pThis->m_cComboBufSelMap[i], nCheckSums[i], nCheckSums[i]);
						}
					}

				}


				goto PCEND;
			}
			//
			else if (1 == buffersInput[2])
			{
				//cancel
				//	strtmp.Format(L"Cancel thread %s\n", __FUNCTIONW__);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 0, pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit);
				pCProgress->SetPos(0);
				//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				cStatus = PROC_CANCEL;
				pThis->m_nIsAuto[nThIdx] = 0;
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
				//pThis->Beep(nThIdx, 0);
				goto PCCANCEL;

			}
			//算法FAIL上报
			else if (2 == buffersInput[2])
			{
				//cancel
				strtmp.Format(L"Fail\n");
				pCProgress->SetPos(0);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				wErrMaskinoneproc = pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
				cStatus = PROC_END;
				//	pThis->m_nIsAuto[nThIdx] = 0;
				goto PCEND;

			}

		}
		//DEBUGSTRING
		else if (buffersInput[0] == 'D')
		{
			if (0xff == ((UCHAR)buffersInput[2]))
			{
				int nColor = (buffersInput[3] << 16) | (buffersInput[4] << 8) | (buffersInput[5]);
				CharToTchar(wsztemp, (const char*)(buffersInput + 2 + 4));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, nColor, 0, 0);
			}
			else
			{
				CharToTchar(wsztemp, (const char*)(buffersInput + 2));
				strtmp.Format(L"%s", wsztemp);
				if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_GREEN, 0, 0);
			}


		}
		//进度条 PROGRESS
		else if (buffersInput[0] == 'P')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			pCProgress->SetPos(nScale);
			g_SerialResBuf[SERSOCKBASE + nSocketMax* 32 + (pThis->m_nSiteNo[nThIdx] - 1)] = nScale;

		}
		else if (buffersInput[0] == 'X')
		{
			memcpy(&nScale, &buffersInput[2], 4);
			memcpy(g_ConfigData.nData, &buffersInput[2], 498);

		}
		//BufferSeek
		else if (buffersInput[0] == 'S')
		{

			memcpy(&nSeekL, &buffersInput[2], 4);
			memcpy(&wBufIdx8_Haddr8, &buffersInput[2 + 4], 2);
			llSeekAddr = (UINT64)(wBufIdx8_Haddr8 &0XFF)<< 32| nSeekL;
			cBufIdx = wBufIdx8_Haddr8 >> 8;

			//获得SN
			if ((cBufIdx & 0x7f) == BUFNUM)
			{

			}
			//写操作的BUFFER NUM与大于MAX
			else if (((cBufIdx & 0x7f) > BUFNUM) && ((cBufIdx & 0x80) == 0))
			{
				strtmp.Format(L"Buffer Idx>%d error\n", BUFNUM);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				pThis->Beep(nThIdx, 2);
				goto PCCANCEL;
			}

			//写操作时DEVICE没有这个BUFFER NUMBER
			else if (((cBufIdx & 0x80) == 0) && ((0 == strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[cBufIdx & 0x7f])) || (0 == strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[cBufIdx & 0x7f]))))
			{
				strtmp.Format(L"Buffer Idx %d Invalid\n", cBufIdx);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, 0XFF);
				pCProgress->SetPos(0);
				cStatus = PROC_CANCEL;
				goto PCCANCEL;
			}
			else if ((0 == (cBufIdx & 0x80)) && ((cBufIdx & 0X7F) == crCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是写操作

				rfile.Seek(llSeekAddr, CFile64::begin, 1);

			}
			else if ((cBufIdx & 0x80) && ((cBufIdx & 0X7F) == cwCurBufIdx))
			{
				//如果是读操作，不直接SEEK。在填充时候加上去,这是读，啥也不干
			}
			//不同要重新打开文件
			else
			{
				//	if (Curfile.IsOpen())
				{
					//无论是否打开，当前读BUFFER idx都要更新
					cwCurBufIdx = cBufIdx & 0X7F;
					//读操作
					if (cBufIdx & 0x80)
					{
						if (wfile.IsOpen())
						{
							wfile.Close();
							strtmp.Format(L"wBuf%d closed", cwCurBufIdx);
							pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
							
							//读直接用路径，不是BUFX
							path = pThis->m_strReadFileDefaultPath[cBufIdx & 0x7f];
							if (rfile.IsOpen())
							{
								if (rfile.GetFileName() == pThis->m_strReadFileDefaultPath[cwCurBufIdx])
								{
									rfile.Close();
								}
							}
							if (!wfile.Open(path, GENERIC_WRITE, 0, OPEN_ALWAYS, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								return 0;
							}
							strtmp.Format(L"buf%d open,seek %d\n", cwCurBufIdx, llSeekAddr);
						}

					}
					//写操作
					else
					{
						if (rfile.IsOpen())
						{
							rfile.Close();
						//	strtmp.Format(L"wBuf%d closed", crCurBufIdx);
						//	pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
						}
							crCurBufIdx = cBufIdx & 0X7F;
							CharToTchar(wszPath, pstuDevInfo[g_curDeviceSel].szBufNameArrs[crCurBufIdx]);
							path.Format(L"%slib\\%s", g_wszCurPath, wszPath);
							path += L".bf";
							if (wfile.IsOpen())
							{
								if (wfile.GetFileName() == path)
								{
									wfile.Close();
								}
							}
							if (!rfile.Open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &e))
							{
								strtmp.Format(L"Failed to open the file %s", e.m_strFileName); pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
								CloseHandle(ovLapStatus.hEvent);
								pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);
								return 0;
							}
							rfile.Seek(llSeekAddr, CFile64::begin, 1);
							strtmp.Format(L"buf%d open,seek %d\n", crCurBufIdx, llSeekAddr);
						
					}


					//读的话，需要在读到数据的时候填充，不要直接SEEK，

					//if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, 0, 0);

				}
			}

		}
		//LED状态显示颜色
		else if (buffersInput[0] == 'W')
		{
			memcpy(&nWarnLed, &buffersInput[2], 4);
			//pCProgress->SetPos(nScale);
			wColoridx = nWarnLed >> 16;
			//低16位是掩码

			if (WARNCOLOR_RED == wColoridx)
			{
				//有错误才显示红灯
				for (i = 0; i < nSocketMax; i++)
				{
					if (nWarnLed&(1 << i))
					{
						//重复SOCKET只显示一次
						if (0 == (wErrMaskinoneproc&(1 << i)))
						{
							if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
							{

								strtmp.Format(L"socket%d Failure", i + 1);
								if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 2);
							}

						}

					}
				}
				wErrMaskinoneproc |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (wErrMaskinoneproc&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_BLUE == wColoridx)
			{
				nNoticeBlue |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticeBlue&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}
			else if (WARNCOLOR_PURPLE == wColoridx)
			{
				nNoticePurple |= (nWarnLed & 0xffff);

				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nNoticePurple&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}

			else
			{
				pThis->pFormView2->LedDisplayEachPanel(nThIdx, wColoridx, ((~pThis->stu_overlap.nOverLapSockFail[nThIdx]) & (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)) & (nWarnLed&(pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)));
			}


		}

		if (ret != true)
		{
			pThis->stu_UsbDeviceArr[nThIdx].status = USBNOTCONNECT;

			//SOCKET设置未连接
			g_SerialResBuf[pThis->m_nSiteNo[nThIdx] - 1] = USBNOTCONNECT;
			memset(&g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax], SER_SOCKET_DISABLE, nSocketMax);
			memset(&pThis->stu_AutoSeq[nThIdx], 0, sizeof(pThis->stu_AutoSeq[nThIdx]));
			cStatus = PROC_ERRSTOP;
			goto USBERR;

		}

	}

PCEND:
	nBtnIdx = pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx];
	pThis->pFormView1->GetDlgItem(pThis->pFormView1->PROCBTN_ARR[nBtnIdx])->GetWindowTextW(strtmp);
	//如果选了叠料
	if (pThis->stu_overlap.nIsOverLapCheck[nThIdx])
	{
		pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Checking", COLOR_YELLOW, 0, 0);
		wErrMaskinoneproc = (~(wErrMaskinoneproc))&(pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit);
		pThis->stu_overlap.nOverLapSockFail[nThIdx] = wErrMaskinoneproc;

		pThis->pFormView2->LedDisplayEachPanel(nThIdx, 2, pThis->stu_overlap.nOverLapSockFail[nThIdx]);
		//如果校验成功，代表叠料了

		if (pThis->stu_overlap.nOverLapSockFail[nThIdx])
		{
			if (pThis->stu_overlap.nOverLapSockFail[nThIdx] == pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
				pThis->pFormView3->RichEditShow(nThIdx, L"Overlap Check Fail", COLOR_RED, 0, 0);

			}
			for (i = 0; i < SOCKETMAX; i++)
			{
				if ((1 << i)&(pThis->stu_overlap.nOverLapSockFail[nThIdx]))
				{
					strtmp.Format(L"Sok %d overlap Fail", i + 1);
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);
				}
			}

		}

	}

	//如果选了空检查出错擦除，第一步是空检查，都OK的情况下，直接跳过下面的ERASE
	else if ((pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nThIdx].nAutoidxArray[pThis->stu_AutoSeq[nThIdx].nCurAutoIdx]] == 'b') && (g_nEraseWhenNOTBlank))
	{
		if (wErrMaskinoneproc == 0)
		{
			pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;
		}
		//g_nEraseWhenNOTBlank==1在BLANK中ERRMASK不能设置1，否则会导致后面退出
		wErrMaskinoneproc = 0;

	}

	//全错，又不是blank且g_nEraseWhenNOTBlank=0，则停止
	if (wErrMaskinoneproc == pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit)
	{
		pThis->m_nIsAuto[nThIdx] = 0;
	}
PCCANCEL:
	pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus |= (wErrMaskinoneproc | pThis->stu_overlap.nOverLapSockFail[nThIdx]);

	pThis->stu_UsbDeviceArr[nThIdx].status = USBCONNECT_IDLE;
USBERR:
	CloseHandle(ovLapStatus.hEvent);
	epBulkCmdIn->Abort();
	epBulkOut->Abort();
	//CloseHandle(OutOvLap.hEvent);
	//取消映射
	if (rfile.IsOpen())
		rfile.Close();
	if (wfile.IsOpen())
	{
		wfile.Close();
	}


	//关闭文件映射对象

	pThis->m_pThreadUsbData[nThIdx] = NULL;

	if (cStatus == PROC_CANCEL)
	{
		strtmp.Empty();
	}
	//如果SOCKET全部报错。就不报下面这些FINISHED了
	if (cStatus != PROC_SOCKETALLERR)
	{
		if (cStatus == PROC_CANCEL)strtmp += L" Canceled";
		else
		{
			if (0 == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" SUCCESS";;
			}
			else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
			{
				strtmp += L" FAIL";
			}
			else
				strtmp += L" FINISHED";
		}
		if (0 == pThis->stu_overlap.nIsOverLapCheck[nThIdx])pThis->pFormView3->RichEditShow(nThIdx, strtmp, OPERATIONCOLOR, 0, 6);
		TimeEnd = CTime::GetCurrentTime();
		Timedif = TimeEnd - TimeBegin;
		delay = Timedif.GetMinutes() * 60 + Timedif.GetSeconds();
		strtmp.Format(L"%d seconds", delay);
		pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
	}

	if ((cStatus == PROC_END) || (cStatus == PROC_CANCEL))
	{
		//AUTO中
		if (pThis->m_nIsAuto[nThIdx])
		{
			//叠料检测那次不++；
			if (pThis->stu_overlap.nIsOverLapCheck[nThIdx] == 0)
			{
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx++;

			}
			else pThis->stu_overlap.nIsOverLapCheck[nThIdx] = 0;


		PRESSURElOOP:


			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx < pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				//中途掉线就不AUTO哦了
				if (pThis->stu_UsbDeviceArr[nThIdx].status != USBNOTCONNECT)
					AfxBeginThread((AFX_THREADPROC)pThis->UsbDataProcFileMap9, (LPVOID)pThis);
			}
			if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;
			}
		}
		//单次或者AUTO最后一次
		if (pThis->m_nIsAuto[nThIdx] == 0)
		{
			//记录本次失败的SOCKET
			pThis->m_FailSktLastAuto[nThIdx] = wErrMaskinoneproc&pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit;
			if (pThis->stu_AutoSeq[nThIdx].nAutoCnt)
			{
				pThis->m_nIsAuto[nThIdx] = 0;

				if (0xff == (pThis->m_nBtnIdx & 0xff))
				{//确保是AUTO
					if (0 == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO SUCCESS";
					}
					else if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit == (wErrMaskinoneproc & pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit))
					{
						strtmp = L"AUTO FAIL";
					}
					else
						strtmp = L"AUTO FINISHED";
					pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
				}
			}
			//统计
			for (i = 0; i < nSocketMax; i++)
			{
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{

					if ((wErrMaskinoneproc | pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus)&(1 << i))
					{

						pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[i]++;
						pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt++;
					}
					pThis->stu_UsbDeviceArr[nThIdx].nSokTotalCnt[i]++;
					pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt++;
				}
			}
			strtmp.Format(L"Total:%d  Success:%d  Fail:%d", pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalCnt - pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt, pThis->stu_UsbDeviceArr[nThIdx].nTotalFailCnt);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 40);
			strtmp.Format(L"SockFail %d,%d,%d,%d,%d,%d,%d,%d", pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[0], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[1], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[2], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[3], \
				pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[4], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[5], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[6], pThis->stu_UsbDeviceArr[nThIdx].nSokFailCnt[7]);
			pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK, CFE_BOLD | CFE_ITALIC, 0);
			pThis->SummaryLog(nThIdx);
			//根据nSockProgStatus ,失败的写回SN 文件
			//if (nNeedDelKey)
			{
				for (nSnChnIdx = 0; nSnChnIdx < pThis->stu_GenSetting.nCnt; nSnChnIdx++)
				{
					if (pThis->stu_UserSNProg[nThIdx][nSnChnIdx].nSnNum > 0)
					{
						idx = 0;
						pThis->m_CriticalSectionLog.Lock();
						for (i = 0; i < SOCKETMAX; i++)
						{
							//SOCKET不为空
							if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit&(1 << i))
							{
								//失败，SN码一一写回
								//失败，从KEYPSD文件夹MOVEBACK
								//char path_buffer[_MAX_PATH];
								TCHAR drive[_MAX_DRIVE];
								TCHAR dir[_MAX_DIR];
								TCHAR fname[_MAX_FNAME];
								TCHAR ext[_MAX_EXT];
								_wsplitpath(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], drive, dir, fname, ext);
								if (pThis->stu_GenSetting.nIsDelete)
								{
									strtmp = g_wszCurPath;
								}
								else
								{
									strtmp = drive;
									strtmp += dir;
								}
								strtmp += L"KPsd\\";
								strtmp += fname;
								strtmp += ext;
								if (0 != (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i)))
								{
#if 0
									if (0 != wcslen(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx]))
									{


										if (0 == MoveFile(strtmp, pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx]))
										{
											strtmp.Format(L"Skt%d,", i + 1);
											strtmp += fname;
											strtmp += L" move back fail";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

										}
										else
										{
											strtmp.Format(L"Skt%d,", i + 1);
											strtmp += fname;
											strtmp += L" move backed";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
										}
										//SnFile.Open(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], CFile::modeCreate | CFile::modeWrite);
										//SnFile.Write(&pThis->stu_UserSNProg[nThIdx][nSnChnIdx].pSNArr[idx*pThis->stu_GenSetting.nUserSnLen[nSnChnIdx]], pThis->stu_GenSetting.nUserSnLen[nSnChnIdx]);
										//SnFile.Close();

									}

									else
									{
										/*AfxMessageBox(L"SN Number empty");
										pThis->m_CriticalSectionSnRd.Unlock();
										break;*/
									}
#endif
								}
								else
								{

									DeleteFile(strtmp);
									if (0 == MoveFile(pThis->stu_UserSNProg[nThIdx][nSnChnIdx].swzSnUsedFile[idx], strtmp))
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										strtmp += L" move fail";
										pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_RED, 0, 0);

									}
									else
									{
										strtmp.Format(L"Skt%d,", i + 1);
										strtmp += fname;
										if (wcslen(fname))
										{

											strtmp += L" moved";
											pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_PINK_CLEAR, 0, 0);
											if (pThis->stu_GenSetting.nIsDelete)
											{
												strtmp = g_wszCurPath;
											}
											else
											{
												strtmp = drive;
												strtmp += dir;
											}

											strtmp += L"KPsd\\";

											pThis->logPsdKey4(strtmp, fname);

										}
									}

								}
								idx++;

							}
						}
						pThis->m_CriticalSectionLog.Unlock();
					}

				}
			}

			if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				//全错 FAIL


				pThis->Beep(nThIdx, 2);


			}
			//成功，无错
			else if (pThis->stu_UsbDeviceArr[nThIdx].ncurLegalSktUnit)
			{
				pThis->Beep(nThIdx, 0);
			}
			//计算时间
			if (cStatus != PROC_SOCKETALLERR)
			{
				pThis->m_TimeEnd[nThIdx] = CTime::GetCurrentTime();
				Timedif = pThis->m_TimeEnd[nThIdx] - pThis->m_TimeBegin[nThIdx];
				delay = Timedif.GetTotalSeconds();
				strtmp.Format(L"Total %d seconds", delay);
				pThis->pFormView3->RichEditShow(nThIdx, strtmp, COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 0);
				pThis->pFormView3->RichEditShow(nThIdx, L"", OPERATIONCOLOR, 0, 0);
			}

			//删除KEY的记录
			for (i = 0; i < 10; i++)
			{
				pThis->stu_UserSNProg[nThIdx][i].nSnNum = 0;
				memset(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile, 0, sizeof(pThis->stu_UserSNProg[nThIdx][i].swzSnUsedFile));
			}
			pThis->HighZ_CloseV(nThIdx);
		}
	}
	if (pThis->m_nIsAuto[nThIdx] == 0)
	{
		//串口 和网络
		if ((stu_RemoteStat.nRemoteStat > 0) && ((TRUE == stu_RemoteStat.isComOpened) || (pThis->m_SocketObject.IsOpen())))
		{

			

			for (i = 0; i < nSocketMax; i++)
			{
				//使能的SOCKET都RUN
				if (pThis->stu_UsbDeviceArr[nThIdx].curSocketUnit&(1 << i))
				{
					//失败的
					if (pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus&(1 << i))
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
					//成功的
					else
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_OK;
					}

				}

				//未使能的，如果是SOCKET ERR=1，是座子号不对
				else
				{
					//if (pThis->stu_UsbDeviceArr[nThIdx].cSokEncRet[i])
					{
						g_SerialResBuf[SERSOCKBASE + (pThis->m_nSiteNo[nThIdx] - 1)*nSocketMax + i] = SER_SOCKET_FAIL;
					}
				}

			}
			g_SerialResBuf[(pThis->m_nSiteNo[nThIdx] - 1)] = SER_PROG_READY;


		}
		pThis->stu_UsbDeviceArr[nThIdx].nSockProgStatus = 0;
	}



	pThis->pFormView1->CntDisplayEachLeftListCtrl(nThIdx, 0);
//	pThis->pFormView2->CntDisplayEachPanel(nThIdx);


	//压力测试
	//如果选择PINCHECK AUTO，使用压力测试的流程，把次数固定
	if (pThis->nAutoSenseAutoRun)
	{
		if (pThis->nAutoSenseAutoRunStartEnd % 2)
		{
			pThis->m_nAutoCntPressure[nThIdx] = 5;
		}
		else
		{
			pThis->m_nAutoCntPressure[nThIdx] = 0;
			pThis->pFormView3->RichEditShow(nThIdx, L"Auto Sensing Finished", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
			pThis->nAutoSenseAutoRunStartEnd = 0;
			pThis->m_pThreadUsbData[nThIdx] = NULL;

		}

	}
	if (pThis->stu_AutoSeq[nThIdx].nCurAutoIdx == pThis->stu_AutoSeq[nThIdx].nAutoCnt)
	{
		if (pThis->m_nAutoCntPressure[nThIdx] > 0)
		{
			nSocketMax = 0;
			pThis->m_nAutoCntPressure[nThIdx]--;
			if (pThis->m_nAutoCntPressure[nThIdx] > 0)
			{
				pThis->m_nIsAuto[nThIdx] = 0xff;
				pThis->stu_AutoSeq[nThIdx].nCurAutoIdx = 0;

				goto PRESSURElOOP;
			}
		}
	}
	return 0;
}
BOOL CMainFrame::AnyprogRunning(int nProgMask)
{
	int i = 0;


	for (i = 0; i < PROGRAMERMAXNUM; i++)
	{
		if (nProgMask&(1 << i))
		{
			if (stu_UsbDeviceArr[i].status == USBCONNECT_RUN)
				return TRUE;
		}
		
	}
	return FALSE;
}
int CMainFrame::IsSnInCurDevSNList(char *pSN)
{
	int ret = 1;
	TCHAR swztmp[256];
	CString strElement;
	POSITION rPos;
	//FFF,都可见的DEVICE
	if (strListSN.GetSize() == 0)
	{
		return 0;
	}
	else
	{		
		CharToTchar(swztmp, pSN);
		rPos = strListSN.GetHeadPosition();
		while (rPos != NULL)
		{
			strElement = strListSN.GetNext(rPos);
			if (strElement == swztmp)
			{
				ret = 0;
				break;
			}
		}
	}
	return ret;
	
}

int CMainFrame::RunUsbDataProc(int nProgMask, int nBtnIdx)
{
	//数据进程启动
	int i = 0;
	int nNeedDataAna=0;
	//有读操作
	int nHasRead= 0;
	int j;
	int ret=0;
	int nRunProgCnt = PROGRAMERMAXNUM;
	

	m_nBtnIdx = nBtnIdx;
	ret = 0; j = 0; i = 0;
	
	
	

	//AUTO
	if (nBtnIdx == 0xff) 
	{
		nNeedDataAna = 0;
		for (i = 0; i < stu_AutoSeqGlob.nAutoCnt; i++)
		{
			if (stu_FuncList.cFuncAttr[stu_AutoSeqGlob.nAutoidxArray[i]] != 'r')
			{
				//AUTO里面不全是READ
				if (m_nIsLoadBufferDll)	nNeedDataAna = 1;
				break;
			}
			else
			{
				//AUTO有读操作
				nHasRead = 1;
			}
		}
		if (m_nIsReadFitnessNeedDataAnalysis)
		{
			if (m_nIsLoadBufferDll)
			{
				CreateDataAnalysis();
				m_nIsReadFitnessNeedDataAnalysis = 0;
			}
		}
		if (nNeedDataAna)
		{
			if (m_nIsLoadBufferDll)
			{
				pFormView2->StartLoadDll();
				m_nIsLoadBufferDll = 0;
			}
				
		}
			
	}
	//读的时候不要算
	//else if (stu_FuncList.cFuncAttr[stu_AutoSeq[0].nAutoidxArray[stu_AutoSeq[0].nCurAutoIdx]] != 'r')
	//单步
	else if (stu_FuncList.cFuncAttr[nBtnIdx] != 'r')
	{
		if (m_nIsLoadBufferDll)
		{
			if (m_nIsReadFitnessNeedDataAnalysis)
			{
				CreateDataAnalysis();
				m_nIsReadFitnessNeedDataAnalysis = 0;
			}
			pFormView2->StartLoadDll();
			m_nIsLoadBufferDll = 0;
		}
	}
	else
	{
		//单步切是读操作
		nHasRead = 1;
	}
	if (nHasRead)
	{
		nRunProgCnt = 1;
		for (i = 0; i < PROGRAMERMAXNUM; i++)
		{
			if (stu_UsbDeviceArr[i].status != USBNOTCONNECT)
			{
				pFormView3->RichEditShow(i, L"Read operation only run in site 1", COLOR_YELLOW, 0, 4);
			}
		}
		
	}
			

#ifndef SPVERSION
	strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], "LFFF");
#endif		
	if (m_nRDskipSokEncSN)
	{
		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], "LFFF");
		
	}
	CreateDownloadData();
	//ONLINE算法运行320和256的选择会变化，所以这里要再确定一次
	ReadAlgo_Fpga_ConfigFromFile2Buf(0, stu_ProjectStatus.nIsInPrj);
	for (i = 0; i < nRunProgCnt; i++)
	{
		if (m_pThreadUsbData[i] == NULL)
		{
			m_nCurDevNo = 0;
			if (i == 0)
			{
				if (pFormView2->m_ProgCheck0.GetCheck() && (nProgMask&(1<<i)))
				{
					if (stu_UsbDeviceArr[0].status == USBCONNECT_IDLE)
					{
						if (0 == IsSnInCurDevSNList(stu_UsbDeviceArr[i].serialNO))
						{
							if ((m_SocketObject.IsOpen()) && (0 == m_SocketObject.m_cMode))
							{
								stu_UsbDeviceArr[0].nIsInRemoteRunning = 1;
							}
#ifdef SNPROGRAM
							//AUTO也要把当前操作项要保存的给保存到buf0
							for (j = 0; j < stu_AutoSeq[0].nAutoCnt; j++)
							{
								pFormView2->SnSaveToBuf0(stu_AutoSeq[0].nAutoidxArray[j]);
							}
							
#endif


							if (0xff==(nBtnIdx&0xff)) pFormView3->RichEditShow(i, L"Auto Begin", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
							m_pThreadUsbData[0] = AfxBeginThread((AFX_THREADPROC)UsbDataProcFileMap0, (LPVOID)this);

						}
						else
						{
							pFormView2->LedDisplayEachPanel(i, 2, 0xffff);
							Beep(i, 2);
							pFormView3->RichEditShow(i, L"SN unavailable", COLOR_RED, 0, 4);
						}
					
					}
						
					
				}
			}
			else if ( i == 1)
			{
				if (pFormView2->m_ProgCheck1.GetCheck() && (nProgMask&(1 << i)))
				{
					if (stu_UsbDeviceArr[i].status == USBCONNECT_IDLE)
					{
						if (0 == IsSnInCurDevSNList(stu_UsbDeviceArr[i].serialNO))
						{
							if ((m_SocketObject.IsOpen()) && (0 == m_SocketObject.m_cMode))
							{
								stu_UsbDeviceArr[i].nIsInRemoteRunning = 1;
							}
							if (0xff==(nBtnIdx&0xff))pFormView3->RichEditShow(i, L"Auto Begin", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
							m_pThreadUsbData[i] = AfxBeginThread((AFX_THREADPROC)UsbDataProcFileMap1, (LPVOID)this);
						}
						else
						{
							pFormView2->LedDisplayEachPanel(i, 2, 0xffff);
							Beep(i, 2);
							pFormView3->RichEditShow(i, L"SN unavailable", COLOR_RED, 0, 4);
						}
					}
				}	
			}

			else if (i == 2)
			{
				if (pFormView2->m_ProgCheck2.GetCheck() && (nProgMask&(1 << i)))
				{
					if (stu_UsbDeviceArr[2].status == USBCONNECT_IDLE)
					{
						if (0 == IsSnInCurDevSNList(stu_UsbDeviceArr[i].serialNO))
						{
							if ((m_SocketObject.IsOpen()) && (0 == m_SocketObject.m_cMode))
							{
								stu_UsbDeviceArr[i].nIsInRemoteRunning = 1;
							}
							if (0xff==(nBtnIdx&0xff))pFormView3->RichEditShow(i, L"Auto Begin", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
							m_pThreadUsbData[i] = AfxBeginThread((AFX_THREADPROC)UsbDataProcFileMap2, (LPVOID)this);
						}
						else
						{
							pFormView2->LedDisplayEachPanel(i, 2, 0xffff);
							Beep(i, 2);
							pFormView3->RichEditShow(i, L"SN unavailable", COLOR_RED, 0, 4);
						}
					}
				}
			}
			else if (i == 3)
			{
				if (pFormView2->m_ProgCheck3.GetCheck() && (nProgMask&(1 << i)))
				{
					if (stu_UsbDeviceArr[i].status == USBCONNECT_IDLE)
					{
						if (0 == IsSnInCurDevSNList(stu_UsbDeviceArr[i].serialNO))
						{
							if ((m_SocketObject.IsOpen()) && (0 == m_SocketObject.m_cMode))
							{
								stu_UsbDeviceArr[i].nIsInRemoteRunning = 1;
							}
							if (0xff==(nBtnIdx&0xff))pFormView3->RichEditShow(i, L"Auto Begin", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
							m_pThreadUsbData[i] = AfxBeginThread((AFX_THREADPROC)UsbDataProcFileMap3, (LPVOID)this);
						}
						else
						{
							pFormView2->LedDisplayEachPanel(i, 2, 0xffff);
							Beep(i, 2);
							pFormView3->RichEditShow(i, L"SN unavailable", COLOR_RED, 0, 4);
						}
					}
				}
			}
			else if (i == 4)
			{
				if (pFormView2->m_ProgCheck4.GetCheck() && (nProgMask&(1 << i)))
				{
					if (stu_UsbDeviceArr[i].status == USBCONNECT_IDLE)
					{
						if (0 == IsSnInCurDevSNList(stu_UsbDeviceArr[i].serialNO))
						{
							if ((m_SocketObject.IsOpen()) && (0 == m_SocketObject.m_cMode))
							{
								stu_UsbDeviceArr[i].nIsInRemoteRunning = 1;
							}
							if (0xff==(nBtnIdx&0xff))pFormView3->RichEditShow(i, L"Auto Begin", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
							m_pThreadUsbData[i] = AfxBeginThread((AFX_THREADPROC)UsbDataProcFileMap4, (LPVOID)this);
						}
						else
						{
							pFormView2->LedDisplayEachPanel(i, 2, 0xffff);
							Beep(i, 2);
							pFormView3->RichEditShow(i, L"SN unavailable", COLOR_RED, 0, 4);
						}
					}
				}
			}
			else if (i == 5)
			{
				if (pFormView2->m_ProgCheck5.GetCheck() && (nProgMask&(1 << i)))
				{
					if (stu_UsbDeviceArr[i].status == USBCONNECT_IDLE)
					{
						if (0 == IsSnInCurDevSNList(stu_UsbDeviceArr[i].serialNO))
						{
							if ((m_SocketObject.IsOpen()) && (0 == m_SocketObject.m_cMode))
							{
								stu_UsbDeviceArr[i].nIsInRemoteRunning = 1;
							}
							if (0xff==(nBtnIdx&0xff))pFormView3->RichEditShow(i, L"Auto Begin", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
							m_pThreadUsbData[i] = AfxBeginThread((AFX_THREADPROC)UsbDataProcFileMap5, (LPVOID)this);
						}
						else
						{
							pFormView2->LedDisplayEachPanel(i, 2, 0xffff);
							Beep(i, 2);
							pFormView3->RichEditShow(i, L"SN unavailable", COLOR_RED, 0, 4);
						}
					}
				}
			}
			else if (i == 6)
			{
				if (pFormView2->m_ProgCheck6.GetCheck() && (nProgMask&(1 << i)))
				{
					if (stu_UsbDeviceArr[i].status == USBCONNECT_IDLE)
					{
						if (0 == IsSnInCurDevSNList(stu_UsbDeviceArr[i].serialNO))
						{
							if ((m_SocketObject.IsOpen()) && (0 == m_SocketObject.m_cMode))
							{
								stu_UsbDeviceArr[i].nIsInRemoteRunning = 1;
							}
							if (0xff==(nBtnIdx&0xff))pFormView3->RichEditShow(i, L"Auto Begin", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
							m_pThreadUsbData[i] = AfxBeginThread((AFX_THREADPROC)UsbDataProcFileMap6, (LPVOID)this);
						}
						else
						{
							pFormView2->LedDisplayEachPanel(i, 2, 0xffff);
							Beep(i, 2);
							pFormView3->RichEditShow(i, L"SN unavailable", COLOR_RED, 0, 4);
						}
					}
				}
			}
			else if (i == 7)
			{
				if (pFormView2->m_ProgCheck7.GetCheck() && (nProgMask&(1 << i)))
				{
					if (stu_UsbDeviceArr[i].status == USBCONNECT_IDLE)
					{
						if (0 == IsSnInCurDevSNList(stu_UsbDeviceArr[i].serialNO))
						{
							if ((m_SocketObject.IsOpen()) && (0 == m_SocketObject.m_cMode))
							{
								stu_UsbDeviceArr[i].nIsInRemoteRunning = 1;
							}
							if (0xff==(nBtnIdx&0xff))pFormView3->RichEditShow(i, L"Auto Begin", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
							m_pThreadUsbData[i] = AfxBeginThread((AFX_THREADPROC)UsbDataProcFileMap7, (LPVOID)this);
						}
						else
						{
							pFormView2->LedDisplayEachPanel(i, 2, 0xffff);
							Beep(i, 2);
							pFormView3->RichEditShow(i, L"SN unavailable", COLOR_RED, 0, 4);
						}
					}
				}
			}
			else if (i == 8)
			{
				if (pFormView2->m_ProgCheck8.GetCheck() && (nProgMask&(1 << i)))
				{
					if (stu_UsbDeviceArr[i].status == USBCONNECT_IDLE)
					{
						if (0 == IsSnInCurDevSNList(stu_UsbDeviceArr[i].serialNO))
						{
							if ((m_SocketObject.IsOpen()) && (0 == m_SocketObject.m_cMode))
							{
								stu_UsbDeviceArr[i].nIsInRemoteRunning = 1;
							}
							if (0xff==(nBtnIdx&0xff))pFormView3->RichEditShow(i, L"Auto Begin", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
							m_pThreadUsbData[i] = AfxBeginThread((AFX_THREADPROC)UsbDataProcFileMap8, (LPVOID)this);
						}
						else
						{
							pFormView2->LedDisplayEachPanel(i, 2, 0xffff);
							Beep(i, 2);
							pFormView3->RichEditShow(i, L"SN unavailable", COLOR_RED, 0, 4);
						}
					}
				}
			}
			else if (i == 9)
			{
				if (pFormView2->m_ProgCheck9.GetCheck() && (nProgMask&(1 << i)))
				{
					if (stu_UsbDeviceArr[i].status == USBCONNECT_IDLE)
					{
						if (0 == IsSnInCurDevSNList(stu_UsbDeviceArr[i].serialNO))
						{
							if ((m_SocketObject.IsOpen()) && (0 == m_SocketObject.m_cMode))
							{
								stu_UsbDeviceArr[i].nIsInRemoteRunning = 1;
							}
							if (0xff==(nBtnIdx&0xff))pFormView3->RichEditShow(i, L"Auto Begin", COLOR_YELLOW, CFE_BOLD | CFE_ITALIC, 40);
							m_pThreadUsbData[i] = AfxBeginThread((AFX_THREADPROC)UsbDataProcFileMap9, (LPVOID)this);
						}
						else
						{
							pFormView2->LedDisplayEachPanel(i, 2, 0xffff);
							Beep(i, 2);
							pFormView3->RichEditShow(i, L"SN unavailable", COLOR_RED, 0, 4);
						}
					}
				}
			}
		}
	}

	return 0;
}
int CMainFrame::CmdSendRcvProc(int nDevNo,PUCHAR pBuf, long size, PUCHAR pGetBuf, PUINT32 getlen)
{

	BYTE inEpAddress = 0x82, outEpAddress = 0x02;
	bool ret = 0;
	PUCHAR		buffersInput = pGetBuf;
	CCyUSBEndPoint *epBulkOut = stu_UsbDeviceArr[nDevNo].pUsbDevice->EndPointOf(outEpAddress);
	CCyUSBEndPoint *epBulkIn = stu_UsbDeviceArr[nDevNo].pUsbDevice->EndPointOf(inEpAddress);
	long writelenth = size;
	long readLenth = 4096;
	if (epBulkOut == NULL || epBulkIn == NULL) return -1;



	epBulkOut->TimeOut = 15000;
	epBulkIn->TimeOut = 15000;

	epBulkOut->SetXferSize(writelenth);

	ret = epBulkOut->XferData(pBuf, writelenth);
	if (ret != true)
	{
		//AfxMessageBox(L"send data error");
		epBulkIn->Abort();
		epBulkOut->Abort();
		return -1;
	}
	else if (writelenth != size)
	{
		AfxMessageBox(L"send data size not match");
		epBulkIn->Abort();
		epBulkOut->Abort();
		return -1;
	}


	ret = epBulkIn->XferData(buffersInput, readLenth);
	if (ret != true)
	{
		//AfxMessageBox(L"read data error");
		epBulkIn->Abort();
		epBulkOut->Abort();
		return -1;

	}
	*getlen = readLenth;
	if (strncmp((char *)buffersInput, "OK", 2) != 0)
	{
		AfxMessageBox(L"USB CMD RESPONSE NOT OK");
		epBulkIn->Abort();
		epBulkOut->Abort();
		return -1;
	}

	epBulkIn->Abort();
	epBulkOut->Abort();


	return 0;

}


int  CMainFrame::SendConfiWord(int nDevNo,int type,UCHAR *pData,int DataLen)
{
	
	UCHAR  buf[256 * 1024];
	UCHAR recbuf[4096];
	CString strtmp;
	CFile algofile;
	UINT  checksum, packlen, reclen, recchecksum;

	buf[1] = (UCHAR)type;


	buf[0] = 'A';

	//head+sizelen+checksumlen
	packlen = DataLen + 2 + 4 + 4;
	//packlen=1030;
	memcpy(&buf[2], &packlen, sizeof(packlen));
	memcpy(&buf[2 + 4], pData, DataLen);

#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));
	
	if (CmdSendRcvProc(nDevNo, buf, packlen, recbuf, &reclen))
	{
		return -1;
	}
	
	if (3 == type)
	{
		//SOCKET对应加密芯片状态
		memcpy(stu_UsbDeviceArr[nDevNo].cSokEncRet, recbuf + 2 + 2 + 4, sizeof(stu_UsbDeviceArr[nDevNo].cSokEncRet));
		//SOCKET号对的MASK.
		memcpy(&stu_UsbDeviceArr[nDevNo].ncurLegalSktUnit, recbuf + 2 + 2 + 4 + 8, sizeof(stu_UsbDeviceArr[nDevNo].ncurLegalSktUnit));
		//PINCHECK status
		memcpy(m_cArrCheckPinStats[nDevNo], recbuf + 2 + 2 + 4 + 8 + sizeof(stu_UsbDeviceArr[nDevNo].ncurLegalSktUnit), sizeof(m_cArrCheckPinStats[nDevNo]));
		//COCKETCHIP RD1
		memcpy(m_cSocketChipRdCnt0[nDevNo], recbuf + 2 + 2 + 4 + 8 + sizeof(stu_UsbDeviceArr[nDevNo].ncurLegalSktUnit) + sizeof(m_cArrCheckPinStats[nDevNo]), sizeof(m_cSocketChipRdCnt0[nDevNo]));
		//COCKETCHIP RD2
		memcpy(m_cSocketChipRdCnt1[nDevNo], recbuf + 2 + 2 + 4 + 8 + sizeof(stu_UsbDeviceArr[nDevNo].ncurLegalSktUnit) + sizeof(m_cArrCheckPinStats[nDevNo]) + sizeof(m_cSocketChipRdCnt0[nDevNo]), sizeof(m_cSocketChipRdCnt1[nDevNo]));
		memcpy(m_wArrCheckPinVols[nDevNo], recbuf + 2 + 2 + 4 + 8 + sizeof(stu_UsbDeviceArr[nDevNo].ncurLegalSktUnit) + sizeof(m_cArrCheckPinStats[nDevNo]) + sizeof(m_cSocketChipRdCnt0[nDevNo]) + sizeof(m_cSocketChipRdCnt1[nDevNo]),sizeof(m_wArrCheckPinVols[nDevNo]));
#ifndef SPVERSION
		stu_UsbDeviceArr[nDevNo].ncurLegalSktUnit = stu_UsbDeviceArr[nDevNo].curSocketUnit;
#endif
	}
	

	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
	}
	
	return 0;
}
UCHAR cCmdSendBufArr[PROGRAMERMAXNUM][4*1024 * 1024];
int  CMainFrame::SendAlgo(int nDevNo,int type,CHAR *pBuf,int nlen)
{
//	UCHAR  *buf=(UCHAR *)malloc(nlen+100);
	UCHAR *buf = cCmdSendBufArr[nDevNo];
	UCHAR recbuf[4096];
	CWin32Heap stringHeap(HEAP_NO_SERIALIZE, 0, 0);
	CAtlStringMgr stringMgr(&stringHeap);
	CString strtmp(&stringMgr);
	
	
	
	CFile algofile;
	int ret=0;
	UINT  checksum, packlen, reclen, recchecksum;
	

	buf[0] = 'A';
	buf[1] = (UCHAR)type;

	//head+sizelen+checksumlen
	packlen = nlen + 2 + 4 + 4;
	//packlen=1030;
	memcpy(&buf[2], &packlen, sizeof(packlen));
	memcpy(&buf[2 + 4], pBuf, nlen);
	//不能发送512字节的倍数
	if (0 == (packlen % 512))
	{
		buf[packlen] = 0;
		
		packlen++;
		memcpy(&buf[2], &packlen, sizeof(packlen));
	}
#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));

	ret=CmdSendRcvProc(nDevNo,buf, packlen, recbuf, &reclen);
	if (ret == 0)
	{
		checksum = CalcCheckSum(recbuf, reclen - 4);
		memcpy(&recchecksum, &recbuf[reclen - 4], 4);
		if (checksum != recchecksum)
		{
			AfxMessageBox(L"rec checksum not match");
			ret = -1;
		}
	
	}
	
	//free(buf);
	return ret;
	
	
}

int  A2BCD(BYTE * pDst, const char * pSrc)
{
	ASSERT(pDst != NULL && pSrc != NULL);
	int n1, n2;
	int nLen = (strlen(pSrc) + 1) / 2;
	for (int i = strlen(pSrc) - 1; i > 0; i -= 2)
	{
		if ((pSrc[i] >= '0') && (pSrc[i] <= '9'))
		{
			n1 = pSrc[i] - '0';
		}
		else
		{
			n1 = pSrc[i] - 'A'+10;
		}
		if ((pSrc[i-1] >= '0') && (pSrc[i-1] <= '9'))
		{
			n2 = pSrc[i-1] - '0';
		}
		else
		{
			n2 = pSrc[i-1] - 'A' + 10;
		}
		//int n2 = pSrc[i - 1] - '0';
		pDst[i / 2] = (n1 & 0xFF) | (n2 << 4);
	}
	if (strlen(pSrc) % 2 != 0)
	{
		if ((pDst[0] >= '0') && (pDst[0] <= '9'))
		{
			pDst[0] = pSrc[0] - '0';
		}
		else
		{
			pDst[0] = pSrc[0] - 'A'+10;
		}
		
	}
	return nLen;
}


void CMainFrame::CreateDownloadData()
{
	
	long long llbufferlen;

	INT *pIntToDnData=(INT *)m_cDownData[0];
	UCHAR cID[4];
	int i=0,l=0,nPosSktName=0;
	int nIsGangSingle = 0;


	//如果是GANG1的设备,只有1SOCKET可以用
	for (i = 0; i < PROGRAMERMAXNUM; i++)
	{
		if ('1'== stu_UsbDeviceArr[i].serialNO[5])
		{
			nIsGangSingle = 1;
			break;
		}

		
	}
	if (nIsGangSingle)
	{
		pFormView3->RichEditShowAll(0, L"Only Socket1 is available\n", COLOR_YELLOW, 0, 8);
		pstuDevInfo[g_curDeviceSel].unit = 1;
		stu_UsbDeviceArr[i].curSocketUnit = 1;
		
	}
	
	i = l = 0;

	memset(cID, 0, sizeof(cID));
	//128 INT config
	memcpy(m_cDownData[0], g_ConfigData.nData, sizeof(g_ConfigData.nData));
	//  1  INT CURSELECT UNIT
	//函数后面	
	//  1  INT UNIT ,用于脱机告诉是几个SKT的算法
	i += sizeof(g_ConfigData.nData) / 4;
	pIntToDnData[i] = pstuDevInfo[g_curDeviceSel].unit;
	//4个BUFFER里的文件的真实SIZE
	i += sizeof(pstuDevInfo[g_curDeviceSel].unit) / 4;
	

	//10个real file  SIZE 低32位
	for (l = 0; l < BUFNUM; l++)
	{
		pIntToDnData[i] = (UINT)m_ullRealFileSize[l];
		i++;
	}

	//个BUFFER SIZE
	for (l = 0; l < BUFNUM; l++)
	{
		sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[l], "%I64x", &llbufferlen);
		pIntToDnData[i] =llbufferlen;
		i++;
	}
	

	//3 int signalpincnt,vccpincnt,gndpincnt
	pIntToDnData[i] = pstuDevInfo[g_curDeviceSel].nSignalPinCnt; i++;
	pIntToDnData[i] = pstuDevInfo[g_curDeviceSel].nVccPinCnt; i++;
	pIntToDnData[i] = pstuDevInfo[g_curDeviceSel].nGndPinCnt; i++;
	//144 signal pins
	for (l = 0; l < pstuDevInfo[g_curDeviceSel].nSignalPinCnt; l++)
	{
		pIntToDnData[i + l] = pstuDevInfo[g_curDeviceSel].nSignalPins[l];
	}
	i += 144;
	//144 VCC 
	
	for (l = 0; l < pstuDevInfo[g_curDeviceSel].nVccPinCnt; l++)
	{
		pIntToDnData[i + l] = pstuDevInfo[g_curDeviceSel].nVccPins[l];
	}
	//最后一个143放debugvalue;
	pIntToDnData[i + 143]= g_nDebugValue;
	i += 144;
	//144 GND PINS
	for (l = 0; l < pstuDevInfo[g_curDeviceSel].nGndPinCnt; l++)
	{
		pIntToDnData[i + l] = pstuDevInfo[g_curDeviceSel].nGndPins[l];
	}
	i += 144 - BUFNUM;
	//6 vccs 
	for (l = 0; l < 6; l++)
	{
		pIntToDnData[i + l] = atoi(m_szVCC[l]);
	}
	i += 6;
	// 3 gnds
	for (l = 0; l < 3; l++)
	{
		pIntToDnData[i + l] = atoi(m_szVIO[l]);
	}
	i += 3;

	//15 INT para
	for (l = 0; l < 15; l++)
	{
		pIntToDnData[i + l] = pstuDevInfo[g_curDeviceSel].nParInts[l];
	}
	i += 15;

	//如果SKT 第三个NAME==LKKK，就不检查
	//测试用,以后要去掉

	//80个字节（20个INT ）的SOCKET NAME
//补丁,号写错了，所以增加一个错号
					 
	if (0 == strncmp("I2300800208", pstuDevInfo[g_curDeviceSel].szSocketName[0], strlen("I2300800208")))
	{
		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], "I230080002081112");
	}
	else if (0 == strncmp("I23008000208", pstuDevInfo[g_curDeviceSel].szSocketName[0], strlen("I23008000208")))
	{
		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], "I230080020801112");
	}
	if (0 == strncmp("I2300800208", pstuDevInfo[g_curDeviceSel].szSocketName[1], strlen("I2300800208")))
	{
		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], "I230080002081112");
	}
	else if (0 == strncmp("I23008000208", pstuDevInfo[g_curDeviceSel].szSocketName[1], strlen("I23008000208")))
	{
		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], "I230080020801112");
	}
	else if (0 == strcmp("I510466504501212", pstuDevInfo[g_curDeviceSel].szSocketName[0]))
	{
		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[1], "I510460650451212");
	}
	else if (0 == strncmp("I51008006008", pstuDevInfo[g_curDeviceSel].szSocketName[0], strlen("I51008006008")))
	{

		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], pstuDevInfo[g_curDeviceSel].szSocketName[0]);
		pstuDevInfo[g_curDeviceSel].szSocketName[3][2] = '2';
	}
	else if (0 == strncmp("I52008006008", pstuDevInfo[g_curDeviceSel].szSocketName[0], strlen("I52008006008")))
	{

		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], pstuDevInfo[g_curDeviceSel].szSocketName[0]);
		pstuDevInfo[g_curDeviceSel].szSocketName[3][2] = '1';
	}
	
	else if (0 == strncmp("I620240050051212", pstuDevInfo[g_curDeviceSel].szSocketName[0], strlen("I62024005005")))
	{
		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], "I210160003001212");
	}
	else if (0 == strncmp("I5602800400411001", pstuDevInfo[g_curDeviceSel].szSocketName[0], strlen("I5602800400411001")))
	{
		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], "I2800400411001");
		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[2], "I002800400411001");
	}
	else if (0 == strncmp("I21016", pstuDevInfo[g_curDeviceSel].szSocketName[0], strlen("I21016")))
	{
		//SOP和SOID一样的号了。都用23,包括SOP8,SOP16
		memcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], pstuDevInfo[g_curDeviceSel].szSocketName[0], sizeof(pstuDevInfo[g_curDeviceSel].szSocketName[0]));
		pstuDevInfo[g_curDeviceSel].szSocketName[3][2] = '3';
		
	}
	else if (0 == strcmp( pstuDevInfo[g_curDeviceSel].szDeviceName, "E521.36"))
	{
		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[1], "I2100800015010002");
	}
	else if (0 == strncmp("I52032006006221012", pstuDevInfo[g_curDeviceSel].szSocketName[0], strlen("I52032006006221012")))
	{
		//ELMOS_E522.48B
		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], "I510320060061210");
	}
	else if (0 == strncmp("I4108001201221110", pstuDevInfo[g_curDeviceSel].szSocketName[0], strlen("I4108001201221110")))
	{
		
		//F28035
		strcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], "I4008001201210003");
	}
#if 0
	//SOIC和SOP兼容
	if (0 == strncmp("I23", pstuDevInfo[g_curDeviceSel].szSocketName[0], strlen("I23")))
	{
		//拷贝NAME0到NAME2,I21添加I23
		memcpy(pstuDevInfo[g_curDeviceSel].szSocketName[2], pstuDevInfo[g_curDeviceSel].szSocketName[0], sizeof(pstuDevInfo[g_curDeviceSel].szSocketName[0]));
		pstuDevInfo[g_curDeviceSel].szSocketName[2][2] = '1';

		if (0 == strncmp("I23", pstuDevInfo[g_curDeviceSel].szSocketName[1], strlen("I23")))
		{
			//拷贝NAME1到NAME3,I23添加I21
			memcpy(pstuDevInfo[g_curDeviceSel].szSocketName[3], pstuDevInfo[g_curDeviceSel].szSocketName[1], sizeof(pstuDevInfo[g_curDeviceSel].szSocketName[1]));
			pstuDevInfo[g_curDeviceSel].szSocketName[3][2] = '1';
		}
	}

#endif

	memcpy(pIntToDnData + i, pstuDevInfo[g_curDeviceSel].szSocketName, sizeof(pstuDevInfo[g_curDeviceSel].szSocketName));
	nPosSktName = i*4;
	i += sizeof(pstuDevInfo[g_curDeviceSel].szSocketName)/sizeof(int);
	//4字节ID
	for (l = 0; l < 4; l++)
	{
		//cID[l] = atoi(pstuDevInfo[g_curDeviceSel].szCID[l]);
		char *pEnd;
		cID[l] = strtol(pstuDevInfo[g_curDeviceSel].szCID[l], &pEnd, 16);
		//A2BCD(&cID[l], pstuDevInfo[g_curDeviceSel].szCID[l]);
	}
	*(pIntToDnData + i) = (cID[0] << 24) | (cID[1] << 16) | (cID[2] << 8) | cID[3];
	i += 1;
	*(pIntToDnData + i) = pstuDevInfo[g_curDeviceSel].isIsp;
	i += 1;
	*(pIntToDnData + i) = pstuDevInfo[g_curDeviceSel].nAdapterMode;
	i += 1;
	*(pIntToDnData + i) =0xff;
	switch (pstuDevInfo[g_curDeviceSel].unit)
	{
		case 1:
			*(pIntToDnData + i) = 0x1;
			break;
		case 2:
			*(pIntToDnData + i)  = 0x3;
			break;
		case 4:
			*(pIntToDnData + i) = 0xf;
			break;
		case 8:
			*(pIntToDnData + i) = 0xff;
			break;
		case 16:
			*(pIntToDnData + i) = 0xffff;
			break;
	}

	i += 1;
	*(pIntToDnData + i) = g_nIsNeedChkId;
	i += 1;

	//if (0 == stu_GenSetting.nCnt)
	{
		for (l = stu_GenSetting.nCnt; l < sizeof(stu_GenSetting.llAddr) / sizeof(long long); l++)
		{
			stu_GenSetting.llAddr[l] = 0;
			stu_GenSetting.nUserSnLen[l] = 0;
		//	stu_GenSetting.nIsDelete = 0;
		}
	}
	memcpy(pIntToDnData + i, stu_GenSetting.llAddr, sizeof(stu_GenSetting.llAddr));
	i += 20;
	memcpy(pIntToDnData + i, stu_GenSetting.nUserSnLen, sizeof(stu_GenSetting.nUserSnLen));
	i += 10;
	*(pIntToDnData + i) = g_nEraseWhenNOTBlank;
	i += 1;
	*(pIntToDnData + i) =( pstuDevInfo[g_curDeviceSel].nIsNeedPinChk&&g_nIsNeedPinChk);
	i += 1;
	*(pIntToDnData + i) = pstuDevInfo[g_curDeviceSel].nIsNeedHighZFPGA;
	i += 1;

	time_t t = time(0);
	
	
	struct tm newtime;
	localtime_s(&newtime, &t);
	

	*(pIntToDnData + i) = (1900 + newtime.tm_year) % 2000;
	i += 1;
	*(pIntToDnData + i) = newtime.tm_mon + 1;
	i += 1;
	*(pIntToDnData + i) = newtime.tm_mday;
	i += 1;
	*(pIntToDnData + i) = newtime.tm_hour;
	i += 1;
	*(pIntToDnData + i) = newtime.tm_min;
	i += 1;
	*(pIntToDnData + i) = newtime.tm_sec;
	i += 1;
	//上次的成功失败,发给下面计数写入芯片里面
	memcpy(pIntToDnData + i, m_FailSktLastAuto, sizeof(m_FailSktLastAuto));
	i += 3;
	//10个real file  SIZE 高32位
	for (l = 0; l < BUFNUM; l++)
	{
		pIntToDnData[i+l] = (UINT)(m_ullRealFileSize[l]>>32);
		
	}
	i += BUFNUM;
	//wcsftime(swzTmp, sizeof(swzTmp), L"%X", p);
	
	//wsprintf(swzTmp, L"%02d%02d%02d", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday);

	//拷贝后面7份，因为cursocketunit（当前选择的）不一样。所以要
	//  1  INT CURSELECT UNIT
	for (i = 1; i < PROGRAMERMAXNUM; i++)
	{
		memcpy(m_cDownData[i], m_cDownData[0], sizeof(m_cDownData[0]));
		
		
	}
	//  1  INT CURSELECT UNIT
	for (i = 0; i < PROGRAMERMAXNUM; i++)
	{
		memcpy(m_cDownData[i] + sizeof(g_ConfigData.nData), &stu_UsbDeviceArr[i].curSocketUnit, sizeof(stu_UsbDeviceArr[i].curSocketUnit));
		if (g_cPwrBrdVer[i][0] != 'C')
		{
			m_cDownData[i][0xc38] = 0;
		}
		/*
		for (l = 0; l < 20; l++)
		{
			if ((0 == memcmp(m_szSkipSokEncSN[l], stu_UsbDeviceArr[i].serialNO, 16))&&strlen(stu_UsbDeviceArr[i].serialNO))
			{
				strcpy((char*)m_cDownData[i] + nPosSktName + 3 * sizeof(pstuDevInfo[g_curDeviceSel].szSocketName[0]), "LFFF");
				break;
			}
		}
		*/
	}
}

void CMainFrame::logsumStr(CString str)
{
	return;
	CString strTmp;
	time_t t = time(0);
	
	TCHAR swzPath[MAX_PATH];
	TCHAR tmp[64];
	


	struct tm newtime;
	localtime_s(&newtime, &t);
	

	wcscpy_s(swzPath, g_wszCurPath);
	wcscat_s(swzPath, L"Log\\");
	wsprintf(tmp, L"%02d%02d%02d_SUM.log", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday);
	wcscat(swzPath, tmp);

	wcsftime(tmp, sizeof(tmp), L"%X", &newtime);
	strTmp.Format(L"%s ", tmp);
	strTmp += str;
	strTmp += L"\n";
	pFormView3->loghelper.WriteLog0(swzPath, strTmp);


	return ;
}


void CMainFrame::logPsdKey0(CString strpath,CString str)
{
	CString strTmp;
	time_t t = time(0);
	

	TCHAR tmp[64];

	struct tm newtime;
	localtime_s(&newtime, &t);

	
	wsprintf(tmp, L"%02d%02d%02d_PsdKey", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday);
	strpath += tmp;
	//wcscat(swzPath, tmp);


	wcsftime(tmp, sizeof(tmp), L"%X", &newtime);
	strTmp.Format(L"%s ", tmp);
	strTmp += str;
	strTmp += L"\n";
	pFormView3->loghelper.WriteKeyLog0(strpath, strTmp);


	return;
}
void CMainFrame::logPsdKey1(CString strpath, CString str)
{
	CString strTmp;
	time_t t = time(0);

	
	TCHAR tmp[64];
	struct tm newtime;
	localtime_s(&newtime, &t);

	wsprintf(tmp, L"%02d%02d%02d_PsdKey", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday);
	strpath += tmp;


	wcsftime(tmp, sizeof(tmp), L"%X", &newtime);
	strTmp.Format(L"%s ", tmp);
	strTmp += str;
	strTmp += L"\n";
	pFormView3->loghelper.WriteKeyLog1(strpath, strTmp);
	return;
}
void CMainFrame::logPsdKey2(CString strpath, CString str)
{
	CString strTmp;
	time_t t = time(0);

	
	TCHAR tmp[64];
	struct tm newtime;
	localtime_s(&newtime, &t);

	wsprintf(tmp, L"%02d%02d%02d_PsdKey", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday);
	strpath += tmp;
	//wcscat(swzPath, tmp);


	wcsftime(tmp, sizeof(tmp), L"%X", &newtime);
	strTmp.Format(L"%s ", tmp);
	strTmp += str;
	strTmp += L"\n";
	pFormView3->loghelper.WriteKeyLog2(strpath, strTmp);
	return;
}
void CMainFrame::logPsdKey3(CString strpath, CString str)
{
	CString strTmp;
	time_t t = time(0);
	
	
	TCHAR tmp[64];
	struct tm newtime;
	localtime_s(&newtime, &t);

	wsprintf(tmp, L"%02d%02d%02d_PsdKey", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday);
	strpath += tmp;
	//wcscat(swzPath, tmp);


	wcsftime(tmp, sizeof(tmp), L"%X", &newtime);
	strTmp.Format(L"%s ", tmp);
	strTmp += str;
	strTmp += L"\n";
	pFormView3->loghelper.WriteKeyLog3(strpath, strTmp);
	return;
}
void CMainFrame::logPsdKey4(CString strpath, CString str)
{
	CString strTmp;
	time_t t = time(0);
	
	
	TCHAR tmp[64];
	struct tm newtime;
	localtime_s(&newtime, &t);;

	wsprintf(tmp, L"%02d%02d%02d_PsdKey", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday);
	strpath += tmp;
	//wcscat(swzPath, tmp);


	wcsftime(tmp, sizeof(tmp), L"%X", &newtime);
	strTmp.Format(L"%s ", tmp);
	strTmp += str;
	strTmp += L"\n";
	pFormView3->loghelper.WriteKeyLog4(strpath, strTmp);
	return;
}
void CMainFrame::logPsdKey5(CString strpath, CString str)
{
	CString strTmp;
	time_t t = time(0);
	
	
	TCHAR tmp[64];
	struct tm newtime;
	localtime_s(&newtime, &t);

	wsprintf(tmp, L"%02d%02d%02d_PsdKey", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday);
	strpath += tmp;
	//wcscat(swzPath, tmp);


	wcsftime(tmp, sizeof(tmp), L"%X", &newtime);
	strTmp.Format(L"%s ", tmp);
	strTmp += str;
	strTmp += L"\n";
	pFormView3->loghelper.WriteKeyLog5(strpath, strTmp);
	return;
}

void CMainFrame::OnTimer(UINT_PTR nIDEvent)
{
	
	char cFrimwareVersion[60];
	char cOnlyFirmware[50];
	int i;
	char cPwBoardV[3] = { 0,0,0 };
	UINT size=0;
	int nProgIdx = 0;
	CString strtmp;
	TCHAR  wszSerialNum0[10];
	TCHAR  wszSerialNum1[50], wszSerialNum2[50], wcPwBoardV[10];
	if (1 == nIDEvent)
	{
		EnumerateEndpointForTheSelectedDevice(0,L"");
			
		KillTimer(nIDEvent);

	}
	else if (2 == nIDEvent)
	{
		KillTimer(nIDEvent);
		//串口
		if ( ReadRemoteStatIni()==2)
		{
			CRemoteCtrlDlg dlg;
			dlg.OpenComFromIni();
			for (i = 0; i < 25; i++)
			{
				pFormView1->GetDlgItem(pFormView1->PROCBTN_ARR[i])->EnableWindow(0);
				
			}
			for (i = 0; i < 6; i++)
			{
				pFormView2->GetDlgItem(stu_UsbDeviceArr[i].CtrlIDarr[22])->EnableWindow(0);
			}
		}
	}

	//
	else if ((4 <= nIDEvent) && (13 >= nIDEvent))
	{
		size = 0;
		nProgIdx = nIDEvent - 4;
		GetFirmware(nProgIdx, cFrimwareVersion);
		memcpy(cOnlyFirmware, cFrimwareVersion + 25, 5);
		cOnlyFirmware[5] = 0;


		CharToTchar(wszSerialNum0, cOnlyFirmware);
		CharToTchar(wszSerialNum1, cFrimwareVersion + 30);
		CharToTchar(wszSerialNum2, cFrimwareVersion + 38);
		memcpy(&size, cFrimwareVersion + 44, 2);
		memcpy(cPwBoardV, cFrimwareVersion + 46, 2);
		if ((cPwBoardV[0] < 'A') || ((cPwBoardV[0] > 'Z')))
		{
			memset(cPwBoardV, 0, sizeof(cPwBoardV));
		}
		memcpy(g_cPwrBrdVer[nProgIdx], cPwBoardV, 2);
		CharToTchar(wcPwBoardV, cPwBoardV);
		
		//strtmp.Format(L"PwBrd:%s", wcPwBoardV);
		strtmp = L"Firmware:";
		//cOnlyFirmware[0] = 0xa;
		if ((cOnlyFirmware[0] < '0') || ((cOnlyFirmware[0] > '0')))
		{
			strtmp += L"...";
			m_nInvalidProgSnTime[nProgIdx]++;
			//如果连续三次Invalid Programmer SN
			if (m_nInvalidProgSnTime[nProgIdx] >= 3)
			{
				strtmp += L"Invalid programmer SN";
				KillTimer(nIDEvent);
			}
		}
		else
		{

			m_nInvalidProgSnTime[nProgIdx] = 0;
			strtmp += wszSerialNum0;
			strtmp += L" ";
			strtmp += wszSerialNum1;
			strtmp += L" ";
			strtmp += wszSerialNum2;
			strtmp += L"  ";
			strtmp += L"drv:";
			strtmp.AppendFormat(L"%d", size);
			strtmp += L"  PwBrd:";
			strtmp += wcPwBoardV;
			
			g_SerialResBuf[(m_nSiteNo[nProgIdx] - 1)] = SER_PROG_READY;

			KillTimer(nIDEvent);
			if (g_isMustUpdateFirmware)
			{
				if (((cOnlyFirmware[0] >= '0') && (cOnlyFirmware[0] <= '9')) && (memcmp(g_szFirmwareVersion, cOnlyFirmware, 5) > 0))
				{
#ifndef SNPROGRAM
					SetTimer(nIDEvent + 10, 1000, NULL);
#endif
				}
				else
				{
					if (g_isMustUpdateUsbDrv)
					{
						if (size != USBDRVSIZE)
						{
#ifndef SNPROGRAM
							SetTimer(nIDEvent + 20, 1000, NULL);
#endif
						}
					}
				}
			}
			else
			{
				if (g_isMustUpdateUsbDrv)
				{
					if (size != USBDRVSIZE)
					{
#ifndef SNPROGRAM
						SetTimer(nIDEvent + 20, 1000, NULL);
#endif
					}
				}
			}
			
		}
		pFormView3->RichEditShow(nProgIdx, strtmp, COLOR_BLUE, 0, 0);
		pFormView3->RichEditShow(nProgIdx, g_wszCapTime, COLOR_BLUE, 0, 0);
		if (g_nCustomerDef)
		{
			strtmp.Format(L"CustomerDef=%d", g_nCustomerDef);
			pFormView3->RichEditShow(nProgIdx, strtmp, COLOR_BLUE, 0, 0);
		}
		

	}
	else if (14 == nIDEvent)
	{
		KillTimer(nIDEvent);
		Updatefirmwaresingle(0);
		
	}
	else if (15 == nIDEvent)
	{
		KillTimer(nIDEvent);
		Updatefirmwaresingle(1);

	}
	else if (16 == nIDEvent)
	{
		KillTimer(nIDEvent);
		Updatefirmwaresingle(2);

	}
	else if (17 == nIDEvent)
	{
		KillTimer(nIDEvent);
		Updatefirmwaresingle(3);

	}
	else if (18 == nIDEvent)
	{
		KillTimer(nIDEvent);
		Updatefirmwaresingle(4);

	}
	else if (19 == nIDEvent)
	{
		KillTimer(nIDEvent);
		Updatefirmwaresingle(5);

	}
	else if ((24 <= nIDEvent) && (33 >= nIDEvent))
	{
		KillTimer(nIDEvent);
		OnUpdateUsbDrvSingle(nIDEvent-24);
	}
#if 1
	else if (50 == nIDEvent)
	{
		//自动确认联动加载文件

		strtmp.LoadStringW(ID_MENU_FUN1);

		KillTimer(50);
		CWnd* hwnd = FindWindow(NULL, strtmp);
		WPARAM wParam;

		wParam = BN_CLICKED;

		wParam <<= 16;   // 左移16位

		wParam |= IDOK;    // 按位或

		LPARAM lParam;

		lParam = (LPARAM)::GetDlgItem(hwnd->GetSafeHwnd(), IDOK);
	
				
		if (hwnd)
		{

			::SendMessage(hwnd->GetSafeHwnd(), WM_COMMAND, wParam, lParam);
			
		}

		
	}
#endif
	//strtmp.Format(L"id=%d,m_nTimeState=%d", nIDEvent, m_nTimeState);
		//pFormView3->RichEditShow(0, strtmp, COLOR_GHOSTWHITE, 0, 0);
	CFrameWnd::OnTimer(nIDEvent);
	
}
void CMainFrame::GetSocketErrInfo(CString &strInfo,char cType,int nsktNum)
{
	switch (cType)
	{
	case 1:
		strInfo.Format(L"Adapter %d connect err", nsktNum);
		break;
	case 2:
		strInfo.Format(L"Adapter %d enccmp err", nsktNum);
		break;
	case 3:
		strInfo.Format(L"Adapter %d SN not match", nsktNum);
		break;
	case 4:
		strInfo.Format(L"Adapter %d count exceed limit",nsktNum);
		break;
	case 5:
		strInfo.Format(L"Adapter %d count <5000 ", nsktNum);
		break;
	case 6:
		strInfo.Format(L"Adapter %d add err", nsktNum);
		break;
	//default:
		//strInfo.Format(L"Adapter %d unknown err", nsktNum);
		//break;

	}
}
int CMainFrame::PinSenseInAuto(int nDev, unsigned short wSktAvailable)
{
	char szSkt0[256] = { 0 }, szSkt1[256] = { 0 }, szSktVol[256] = { 0 };
	//int ucballidx = 0;
	//一个SOCKET有几个空PIN
	int nChipEmpty = 0;
			
	int mapsocketsta[SOCKETMAX][10], mapsocketpinvols[SOCKETMAX][10];
	CString strTmp, strTmp1, strTmpVol;
	int nSokCnt = 0;
	UCHAR* pSokLoc;
	memset(mapsocketsta, 0, sizeof(mapsocketsta));
	memset(mapsocketpinvols, 0, sizeof(mapsocketpinvols));
	//PINCHECK

	switch (pstuDevInfo[g_curDeviceSel].unit)
	{
	case 1:
		pSokLoc = SocMap1[0];
		nSokCnt = 1;
		break;
	case 0x2:
		pSokLoc = SocMap2[pstuDevInfo[g_curDeviceSel].nAdapterMode];
		nSokCnt = 2;
		break;
	case 4:
		pSokLoc = SocMap4[pstuDevInfo[g_curDeviceSel].nAdapterMode];
		nSokCnt = 4;
		if (pstuDevInfo[g_curDeviceSel].nAdapterMode == 1)
		{
			//如TSOP48
			if (wSktAvailable & 1)	wSktAvailable = wSktAvailable | (1 << 4);
			if (wSktAvailable & 2)  wSktAvailable = wSktAvailable | (2 << 4);
			if (wSktAvailable & 4)  wSktAvailable = wSktAvailable | (4 << 4);
			if (wSktAvailable & 8)  wSktAvailable = wSktAvailable | (8 << 4);
			pSokLoc = SocMap8[0];
			nSokCnt = 8;

		}
		break;

	case 8:
	case 16:
		pSokLoc = SocMap8[pstuDevInfo[g_curDeviceSel].nAdapterMode];
		nSokCnt = 8;
		break;
	}
	int k, i, j;
	int nPinIdx;
	for (k = 0; k < 10; k++)
	{
		nPinIdx = pstuDevInfo[g_curDeviceSel].nSignalPins[k];
		if (nPinIdx)
		{
			//	printf("check pin=%x  ",nSignalPins[k]);

			for (i = 0; i < SOCKETMAX; i++)
			{
				//	if (m_cArrCheckPinStats[nDev][k][i])
				{
					//	printf("cres%d=%x ",i,cPinRes[i]);
					for (j = 0; j < nSokCnt; j++)
					{
						//	printf("pSokLoc%d=%x ",j,pSokLoc[j]);
						if (pSokLoc[j] == i)
						{
							//	strTmp.Format(L"IO %d in soket %d", nPinIdx , j + 1);
							//	pFormView3->RichEditShow(0, strTmp, COLOR_YELLOW, 0, 0);
							if (m_cArrCheckPinStats[nDev][k][i])
							{
								mapsocketsta[j][nPinIdx - 1] = m_cArrCheckPinStats[nDev][k][i];

							}
							mapsocketpinvols[j][nPinIdx - 1] = m_wArrCheckPinVols[nDev][k][i];
							break;

						}
					}
				}
			}
		}
	}

	int nSocketNOcon = 0, nSocketPinOpenToPV = 0;
	int idx = 0;

	for (i = 0; i < SOCKETMAX; i++)
	{
		nChipEmpty = 0;
		nSocketPinOpenToPV = 0;
		nSocketNOcon = 0;
		if (wSktAvailable & (1 << i))
		{
			idx = 0;
			strTmp.Format(L"Sok %d unconnect pins ---", i + 1);
			strTmp1.Format(L"Sok %d pins short to PV ---", i + 1);
			strTmpVol.Format(L"Sok %d pins vol ---", i + 1);
			sprintf(szSkt0, "Sok %d unconnect pins ---", 2 * i + 1);
			sprintf(szSkt1, "Sok %d unconnect pins ---", 2 * i + 2);
			sprintf(szSktVol, "pins vol---");

			for (j = 0; j < 10; j++)
			{

				if (pstuDevInfo[g_curDeviceSel].nSignalPins[idx] - 1 == j)
				{
					//对比了才能下一个
					idx++;
					if (mapsocketsta[i][j] == 0)
					{
						nSocketNOcon = 1;
						strTmp.AppendFormat(L"%d,", j + 1);
						//nDev是proger
						//i,是8SOCKET的IDX
						//j,是PIN
						

					}
					//管脚对电源断路，一般是选错了PVX
					else if (mapsocketsta[i][j] == 2)
					{
						nSocketPinOpenToPV = 1;
						strTmp1.AppendFormat(L"%d,", j + 1);
					}
					//当前管脚PIN 电压=0
					if (pstuDevInfo[g_curDeviceSel].nLowVolAutoSense > mapsocketpinvols[i][j])
					{
						nChipEmpty++;
					}
				}
				
				strTmpVol.AppendFormat(L"%d,", mapsocketpinvols[i][j]);
				sprintf(szSktVol + strlen(szSktVol), "%d,", mapsocketpinvols[i][j]);
			}
		

			if (nSocketNOcon)
			{
			//	pFormView3->RichEditShow(nDev, strTmp, COLOR_YELLOW, 0, 0);
				/************************/

			}
			if (1 == g_nDebugValue)
			{
				pFormView3->RichEditShow(nDev, strTmpVol, COLOR_YELLOW, 0, 0);
			}

			if (nSocketPinOpenToPV)
			{
				pFormView3->RichEditShow(nDev, strTmp1, COLOR_YELLOW, 0, 0);
			}
		}
		if (nChipEmpty > 2)
		{
			//有两个PIN就算芯片取走，开始闪灯
			pFormView2->StartBlink(nDev, i);
		}
		else if (nChipEmpty == 0)
		{
			pFormView2->EndBlink(nDev, i);
		}

	}
	

	return nSokCnt;
}
int CMainFrame::PinCheck(int nDev,unsigned short wSktAvailable)
{
	char szSkt0[256] = { 0 }, szSkt1[256] = { 0 }, szSktVol[256] = {0};
	//int ucballidx = 0;
	memset(ucballloc[nDev], 0, sizeof(ucballloc[nDev]));
	ucszText[nDev][0] = 0;


	typedef void(__stdcall* cahngeb)(int, int, char*);
	cahngeb change=NULL;
	if (50==g_nDebugValue)
	{
		if (m_dllhandleConnectDlg)
		{
			typedef void(__stdcall* cahngeb)(int, int, char*);
			 change = (cahngeb)(GetProcAddress(m_dllhandleConnectDlg, "changeBall"));
			
		}
	}
	
	int mapsocketsta[SOCKETMAX][10],mapsocketpinvols[SOCKETMAX][10];
	CString strTmp, strTmp1,strTmpVol;
	int nSokCnt=0;
	UCHAR *pSokLoc;
	memset(mapsocketsta, 0, sizeof(mapsocketsta));
	memset(mapsocketpinvols, 0, sizeof(mapsocketpinvols));
	//PINCHECK

	switch (pstuDevInfo[g_curDeviceSel].unit)
	{
	case 1:
		pSokLoc = SocMap1[0];
		nSokCnt = 1;
		break;
	case 0x2:
		pSokLoc = SocMap2[pstuDevInfo[g_curDeviceSel].nAdapterMode];
		nSokCnt = 2;
		break;
	case 4:
		pSokLoc = SocMap4[pstuDevInfo[g_curDeviceSel].nAdapterMode];
		nSokCnt = 4;
		if (pstuDevInfo[g_curDeviceSel].nAdapterMode == 1)
		{
			//如TSOP48
			if (wSktAvailable & 1)	wSktAvailable = wSktAvailable | (1 << 4);
			if (wSktAvailable & 2)  wSktAvailable = wSktAvailable | (2 << 4);
			if (wSktAvailable & 4)  wSktAvailable = wSktAvailable | (4 << 4);
			if (wSktAvailable & 8)  wSktAvailable = wSktAvailable | (8 << 4);
			pSokLoc = SocMap8[0];
			nSokCnt = 8;

		}
		break;

	case 8:
	case 16:
		pSokLoc = SocMap8[pstuDevInfo[g_curDeviceSel].nAdapterMode];
		nSokCnt = 8;
		break;
	}
	int k,i,j;
	int nPinIdx;
	for (k = 0; k < 10; k++)
	{
		nPinIdx = pstuDevInfo[g_curDeviceSel].nSignalPins[k];
		if (nPinIdx)
		{
			//	printf("check pin=%x  ",nSignalPins[k]);

			for (i = 0; i < SOCKETMAX; i++)
			{
			//	if (m_cArrCheckPinStats[nDev][k][i])
				{
					//	printf("cres%d=%x ",i,cPinRes[i]);
					for (j = 0; j < nSokCnt; j++)
					{
						//	printf("pSokLoc%d=%x ",j,pSokLoc[j]);
						if (pSokLoc[j] == i)
						{
						//	strTmp.Format(L"IO %d in soket %d", nPinIdx , j + 1);
						//	pFormView3->RichEditShow(0, strTmp, COLOR_YELLOW, 0, 0);
							if (m_cArrCheckPinStats[nDev][k][i])
							{
								mapsocketsta[j][nPinIdx - 1] = m_cArrCheckPinStats[nDev][k][i];
								
							}
							mapsocketpinvols[j][nPinIdx - 1] = m_wArrCheckPinVols[nDev][k][i];
							break;
							
						}
					}
				}
			}
		}
	}
	
	int nSocketNOcon = 0,nSocketPinOpenToPV=0;
	int idx = 0;
	for (i = 0; i < SOCKETMAX; i++)	
	{
		nSocketPinOpenToPV = 0;
		nSocketNOcon = 0;
		if (wSktAvailable&(1 << i))
		{
			idx = 0;
			strTmp.Format(L"Sok %d unconnect pins ---", i + 1);
			strTmp1.Format(L"Sok %d pins short to PV ---", i + 1);
			strTmpVol.Format(L"Sok %d pins vol ---", i + 1);
			sprintf(szSkt0, "Sok %d unconnect pins ---", 2*i + 1);
			sprintf(szSkt1, "Sok %d unconnect pins ---", 2 * i + 2);
			sprintf(szSktVol, "pins vol---");
			
			for (j = 0; j < 10; j++)
			{
				
				if (pstuDevInfo[g_curDeviceSel].nSignalPins[idx] - 1 == j)
				{
					//对比了才能下一个
					idx++;
					if (mapsocketsta[i][j]==0)
					{
						nSocketNOcon = 1;
						strTmp.AppendFormat(L"%d,", j + 1);
						//nDev是proger
						//i,是8SOCKET的IDX
						//j,是PIN
						if (50==g_nDebugValue)
						{
							if (m_dllhandleConnectDlg)
							{
								
								char* color("red");

						
								if (j < 5)
								{
									sprintf(szSkt0+strlen(szSkt0), "%d,", j + 1);
									ucballloc[nDev][2 * i] = 1;
									
								}
								
								else
								{
									sprintf(szSkt1 + strlen(szSkt1), "%d,", j + 1);
									ucballloc[nDev][2 * i+1] = 1;
								}
									//change(pStu_YHY16_SiteP[nDev][2 * i+1].x, pStu_YHY16_SiteP[nDev][2 * i+1].y, "red");
							}
						}
						
					}
					//管脚对电源断路，一般是选错了PVX
					else if (mapsocketsta[i][j] ==2)
					{
						nSocketPinOpenToPV = 1;
						strTmp1.AppendFormat(L"%d,", j + 1);
					}
					
					
					
				}
				strTmpVol.AppendFormat(L"%d,", mapsocketpinvols[i][j]);
				sprintf(szSktVol + strlen(szSktVol), "%d,", mapsocketpinvols[i][j]);
			}
			strcat(ucszText[nDev], szSkt0);
			strcat(ucszText[nDev], "\r\n");
			strcat(ucszText[nDev], szSkt1);
			strcat(ucszText[nDev], "\r\n");
			strcat(ucszText[nDev], szSktVol);
			strcat(ucszText[nDev], "\r\n");
			//TcharToChar(ucszText[nDev] + strlen(ucszText[nDev]), strTmp.GetBuffer());
			//strcat(ucszText[nDev], "\r\n");
			//TcharToChar(ucszText[nDev] + strlen(ucszText[nDev]), strTmpVol.GetBuffer());
			//strcat(ucszText[nDev], "\r\n");
			if (nSocketNOcon)
			{
				pFormView3->RichEditShow(nDev, strTmp, COLOR_YELLOW, 0, 0);
				/************************/
				if (50==g_nDebugValue)
				{
#ifdef CONSOLE_ENABLE
					char szTmp[256];
					sprintf(szTmp, "Site%d,", nDev + 1);
					TcharToChar(szTmp + strlen(szTmp), strTmp.GetBuffer());
					strcat(szTmp, "\n");
					cprintf(szTmp);
#endif
					pFormView3->RichEditShow(nDev, strTmpVol, COLOR_YELLOW, 0, 0);
					
				}
				
				/************************/
			}
			 if (1 == g_nDebugValue)
			{
				pFormView3->RichEditShow(nDev, strTmpVol, COLOR_YELLOW, 0, 0);
			}
			
			if (nSocketPinOpenToPV)
			{
				pFormView3->RichEditShow(nDev, strTmp1, COLOR_YELLOW, 0, 0);
			}
		}


	}
	if (50==g_nDebugValue)
	{
	//	m_CriticaUcSetballs.Lock();
		//TcharToChar(ucszText[nDev], strTmpVol.GetBuffer());
		::SendMessage(GetSafeHwnd(), WM_COMM_BALL0 + nDev, (WPARAM)NULL, (LPARAM)NULL);
	//	m_CriticaUcSetballs.Unlock();
	}
	
	return nSokCnt;
}


#if 1
__forceinline int  CMainFrame::DownloadConfig_GetPincheck(int nProg)
{
	int ret;
	int i;
	int nProgIdx = nProg;
	CString strtmp;
	while (1)
	{
		//下载config.同时检查适配器号
		
		ret = SendConfiWord(nProgIdx, 3, m_cDownData[nProgIdx], sizeof(m_cDownData[nProgIdx]));
		if (ret)break;
		if (0 == strcmp(pstuDevInfo[g_curDeviceSel].szSocketName[3], "LFFF"))
		{
			memset(stu_UsbDeviceArr[nProgIdx].cSokEncRet, 0, sizeof(stu_UsbDeviceArr[0].cSokEncRet));
			stu_UsbDeviceArr[nProgIdx].ncurLegalSktUnit = stu_UsbDeviceArr[nProgIdx].curSocketUnit;
		}
		else
		{
			if (pstuDevInfo[g_curDeviceSel].unit == 4)
			{
				strtmp.Format(L"%d,%d,%d,%d", m_cSocketChipRdCnt0[nProgIdx][0], m_cSocketChipRdCnt0[nProgIdx][1],
					m_cSocketChipRdCnt0[nProgIdx][2], m_cSocketChipRdCnt0[nProgIdx][3]);
				pFormView3->RichEditShow(nProgIdx, strtmp, COLOR_YELLOW, 0, 4);

				strtmp.Format(L"%d,%d,%d,%d", m_cSocketChipRdCnt1[nProgIdx][0], m_cSocketChipRdCnt1[nProgIdx][1],
					m_cSocketChipRdCnt1[nProgIdx][2], m_cSocketChipRdCnt1[nProgIdx][3]);
				pFormView3->RichEditShow(nProgIdx, strtmp, COLOR_YELLOW, 0, 4);
			}
			else
			{
				//socket 加密芯片读取次数
				strtmp.Format(L"%d,%d,%d,%d,%d,%d,%d,%d", m_cSocketChipRdCnt0[nProgIdx][0], m_cSocketChipRdCnt0[nProgIdx][1],
					m_cSocketChipRdCnt0[nProgIdx][2], m_cSocketChipRdCnt0[nProgIdx][3],
					m_cSocketChipRdCnt0[nProgIdx][4], m_cSocketChipRdCnt0[nProgIdx][5],
					m_cSocketChipRdCnt0[nProgIdx][6], m_cSocketChipRdCnt0[nProgIdx][7]);
				pFormView3->RichEditShow(nProgIdx, strtmp, COLOR_YELLOW, 0, 4);

				strtmp.Format(L"%d,%d,%d,%d,%d,%d,%d,%d", m_cSocketChipRdCnt1[nProgIdx][0], m_cSocketChipRdCnt1[nProgIdx][1],
					m_cSocketChipRdCnt1[nProgIdx][2], m_cSocketChipRdCnt1[nProgIdx][3],
					m_cSocketChipRdCnt1[nProgIdx][4], m_cSocketChipRdCnt1[nProgIdx][5],
					m_cSocketChipRdCnt1[nProgIdx][6], m_cSocketChipRdCnt1[nProgIdx][7]);
				pFormView3->RichEditShow(nProgIdx, strtmp, COLOR_YELLOW, 0, 4);
			}

			//因为加密导致SOCKETSELECT 有变
			if (stu_UsbDeviceArr[nProgIdx].curSocketUnit != stu_UsbDeviceArr[nProgIdx].ncurLegalSktUnit)
			{
				m_strSktNearLmt[nProgIdx].Empty();
				for (i = 0; i < SOCKETMAX; i++)
				{
					if (stu_UsbDeviceArr[nProgIdx].curSocketUnit & (1 << i))
					{
						if (0 == (stu_UsbDeviceArr[nProgIdx].ncurLegalSktUnit & (1 << i)))
						{
							//返回有要禁止的SOCKET
						//	if (stu_UsbDeviceArr[nProgIdx].cSokEncRet[i])
							{
								GetSocketErrInfo(strtmp, stu_UsbDeviceArr[nProgIdx].cSokEncRet[i], i + 1);
								pFormView3->RichEditShow(nProgIdx, strtmp, COLOR_RED, 0, 4);
								stu_UsbDeviceArr[nProgIdx].nSockProgStatus |= (1 << i);
							}
						}
						else
						{
							//快到限制了是5  或者OK的就是0
							if (stu_UsbDeviceArr[nProgIdx].cSokEncRet[i]==5)
							{
								strtmp.Format(L"Adapter %d left count <5000 ", i + 1);
								m_strSktNearLmt[nProgIdx].AppendFormat(L"SITE%d Adapter %d left<5000\r\n", m_nSiteNo[nProgIdx],i + 1);
								pFormView3->RichEditShow(nProgIdx, strtmp, COLOR_YELLOW, 0, 4);
							}
							else if(stu_UsbDeviceArr[nProgIdx].cSokEncRet[i] == 7)
							{
								strtmp.Format(L"Adapter %d left count <2000 ", i + 1);
								m_strSktNearLmt[nProgIdx].AppendFormat(L"SITE%d Adapter %d left<2000\r\n", m_nSiteNo[nProgIdx], i + 1);
								pFormView3->RichEditShow(nProgIdx, strtmp, COLOR_YELLOW, 0, 4);
							}
							
						}
					}
				}
				pFormView2->LedDisplayEachPanel(nProgIdx, 2, stu_UsbDeviceArr[nProgIdx].curSocketUnit ^ stu_UsbDeviceArr[nProgIdx].ncurLegalSktUnit);
				Beep(nProgIdx, 2);

			}
		}
		if (pstuDevInfo[g_curDeviceSel].nIsNeedPinChk && g_nIsNeedPinChk)
		{
			if (g_cPwrBrdVer[nProgIdx][0] == 'C')
			{
				PinCheck(nProgIdx, stu_UsbDeviceArr[nProgIdx].ncurLegalSktUnit);
			}
			else
			{
#ifndef ONLINE
				pFormView3->RichEditShow(nProgIdx, L"PinCheck unavailable", COLOR_YELLOW, CFE_BOLD, 8);
#endif
			}
		}
		break;
	}
	return ret;
}
#endif
__forceinline DWORD WINAPIV CMainFrame::Downloadthread(LPVOID lParam)
{
	int nProgIdx = *(int *)lParam;
	int i;
	CString strtmp;
	CMainFrame* pThis = (CMainFrame*)AfxGetApp()->m_pMainWnd;

	int ret = 0;

	if (g_isProgramOnline)
	{
		//等待文件传输线程运行到等待USB。
		//WaitForSingleObject(pThis->hEvent[0], INFINITE);
		//下发算法
		if (USBCONNECT_RUN == pThis->stu_UsbDeviceArr[nProgIdx].status)
		{
			while (1)
			{
				Sleep(THDLY);
					//单步或者AUTO 第一步,才需要下载算法。FPGA等。AUTO的后面几步就不需要了//叠料//非空擦除第一次擦除
				if ((pThis->m_nIsAuto[nProgIdx] == 0) || ((pThis->m_nIsAuto[nProgIdx]) && (pThis->stu_AutoSeq[nProgIdx].nCurAutoIdx == 0)) || pThis->stu_overlap.nIsOverLapCheck[nProgIdx] ||
					(g_nEraseWhenNOTBlank && ('e' == pThis->stu_FuncList.cFuncAttr[pThis->stu_AutoSeq[nProgIdx].nAutoidxArray[pThis->stu_AutoSeq[nProgIdx].nCurAutoIdx]])))
				{
					ret = pThis->SendAlgo(nProgIdx, 0, pThis->m_pAlgoData, pThis->m_nAlgoLen);
					if (ret)break;
					if (strlen(pstuDevInfo[g_curDeviceSel].szFpga0))
					{
						if (pThis->stu_UsbDeviceArr[nProgIdx].cIsFPGA256)
							ret = pThis->SendAlgo(nProgIdx, 1, pThis->m_pFpga0Data_256, pThis->m_nFpga0Len_256);
						else
							ret = pThis->SendAlgo(nProgIdx, 1, pThis->m_pFpga0Data_320, pThis->m_nFpga0Len_320);

						if (ret)break;
					}

					if (strlen(pstuDevInfo[g_curDeviceSel].szFpga1))
					{
						if (pThis->stu_UsbDeviceArr[nProgIdx].cIsFPGA256)
							ret = pThis->SendAlgo(nProgIdx, 2, pThis->m_pFpga1Data_256, pThis->m_nFpga1Len_256);
						else
							ret = pThis->SendAlgo(nProgIdx, 2, pThis->m_pFpga1Data_320, pThis->m_nFpga1Len_320);

						if (ret)break;
					}



					if (strlen(pstuDevInfo[g_curDeviceSel].szFpga2))
					{
						if (pThis->stu_UsbDeviceArr[nProgIdx].cIsFPGA256)
							ret = pThis->SendAlgo(nProgIdx, 6, pThis->m_pFpga2Data_256, pThis->m_nFpga2Len_256);
						else
							ret = pThis->SendAlgo(nProgIdx, 6, pThis->m_pFpga2Data_320, pThis->m_nFpga2Len_320);


						if (ret)break;
					}
					if (strlen(pstuDevInfo[g_curDeviceSel].szFpga3))
					{
						if (pThis->stu_UsbDeviceArr[nProgIdx].cIsFPGA256)
							ret = pThis->SendAlgo(nProgIdx, 7, pThis->m_pFpga3Data_256, pThis->m_nFpga3Len_256);
						else
							ret = pThis->SendAlgo(nProgIdx, 7, pThis->m_pFpga3Data_320, pThis->m_nFpga3Len_320);
						if (ret)break;
					}


					pThis->m_TimeBegin[nProgIdx] = CTime::GetCurrentTime();
				}


				if (pThis->stu_overlap.nIsOverLapCheck[nProgIdx])
				{
					ret = pThis->UsbUserProc(nProgIdx, pThis, pThis->stu_overlap.nOverLapCheckIdx);
				}
				else
				{

					ret = pThis->UsbUserProc(nProgIdx, pThis, pThis->stu_AutoSeq[nProgIdx].nAutoidxArray[pThis->stu_AutoSeq[nProgIdx].nCurAutoIdx]);
				}
				if (ret)break;

				break;
			}


			pThis->m_pThreadUserProc1[nProgIdx] = NULL;
			if (ret)
			{
				pThis->pFormView3->RichEditShow(nProgIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
				//AfxMessageBox(L"cmd Transfer Err0");

			}

		}

	}
	return 0;
}



__forceinline DWORD  CMainFrame::UsbUserProc(int nProg,LPVOID lParam, UCHAR cIdx)
{
	CMainFrame* pThis = (CMainFrame*)lParam;

	UCHAR buf[256 * 1024];
	UCHAR recbuf[4096];
	CString strtmp;

	UINT checksum, packlen, reclen, recchecksum;
	pThis->pFormView1->GetDlgItem(IDC_BTN_PROC1)->GetWindowText(strtmp);
	if (strtmp.IsEmpty())return -1;

	buf[0] = 'B';
	buf[1] = cIdx;

	//strtmp.Format(L"autoidx=%d", buf[1]);
	//pThis->pFormView3->RichEditShow(0,strtmp, COLOR_YELLOW, 0, 0);
	//head+sizelen+checksumlen
	packlen = +2 + 4 + 4;
	memcpy(&buf[2], &packlen, sizeof(packlen));
#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));

	if (pThis->CmdSendRcvProc(nProg, buf, packlen, recbuf, &reclen))
	{

		pThis->pFormView3->RichEditShow(0, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		pThis->m_pThreadUserProc1[nProg] = NULL;
		return -1;

	}
	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
	}
	pThis->m_pThreadUserProc1[nProg] = NULL;
	return 0;
}

void WINAPIV CMainFrame::RunCmdCancel0(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR buf[256 * 1024];
	UCHAR recbuf[4096];
	CString strtmp;

	UINT checksum, packlen, reclen, recchecksum;

	
	buf[0] = 'C';
	buf[1] = 1;
	//head+sizelen+checksumlen
	packlen = +2 + 4 + 4;
	memcpy(&buf[2], &packlen, sizeof(packlen));
#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));


	if (pThis->CmdSendRcvProc(0, buf, packlen, recbuf, &reclen))
	{

		pThis->pFormView3->RichEditShow(0, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		
		return;

	}
	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
	}
	return;
}
void WINAPIV CMainFrame::RunCmdCancel1(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR buf[256 * 1024];
	UCHAR recbuf[4096];
	CString strtmp;

	UINT checksum, packlen, reclen, recchecksum;


	buf[0] = 'C';
	buf[1] = 1;
	//head+sizelen+checksumlen
	packlen = +2 + 4 + 4;
	memcpy(&buf[2], &packlen, sizeof(packlen));
#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));

	if (pThis->CmdSendRcvProc(1, buf, packlen, recbuf, &reclen))
	{

		pThis->pFormView3->RichEditShow(1, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);

		return;

	}
	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
	}
	return;
}
void WINAPIV CMainFrame::RunCmdCancel2(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR buf[256 * 1024];
	UCHAR recbuf[4096];
	CString strtmp;

	UINT checksum, packlen, reclen, recchecksum;


	buf[0] = 'C';
	buf[1] = 1;
	//head+sizelen+checksumlen
	packlen = +2 + 4 + 4;
	memcpy(&buf[2], &packlen, sizeof(packlen));
#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));

	if (pThis->CmdSendRcvProc(2, buf, packlen, recbuf, &reclen))
	{

		pThis->pFormView3->RichEditShow(2, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);

		return;

	}
	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
	}
	return;
}
void WINAPIV CMainFrame::RunCmdCancel3(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR buf[256 * 1024];
	UCHAR recbuf[4096];
	CString strtmp;

	UINT checksum, packlen, reclen, recchecksum;


	buf[0] = 'C';
	buf[1] = 1;
	//head+sizelen+checksumlen
	packlen = +2 + 4 + 4;
	memcpy(&buf[2], &packlen, sizeof(packlen));
#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));

	if (pThis->CmdSendRcvProc(3, buf, packlen, recbuf, &reclen))
	{

		pThis->pFormView3->RichEditShow(3, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);

		return;

	}
	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
	}
	return;
}
void WINAPIV CMainFrame::RunCmdCancel4(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR buf[256 * 1024];
	UCHAR recbuf[4096];
	CString strtmp;

	UINT checksum, packlen, reclen, recchecksum;


	buf[0] = 'C';
	buf[1] = 1;
	//head+sizelen+checksumlen
	packlen = +2 + 4 + 4;
	memcpy(&buf[2], &packlen, sizeof(packlen));
#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));


	if (pThis->CmdSendRcvProc(4, buf, packlen, recbuf, &reclen))
	{

		pThis->pFormView3->RichEditShow(4, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);

		return;

	}
	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
	}
	return;
}

void WINAPIV CMainFrame::RunCmdCancel5(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR buf[256 * 1024];
	UCHAR recbuf[4096];
	CString strtmp;

	UINT checksum, packlen, reclen, recchecksum;


	buf[0] = 'C';
	buf[1] = 1;
	//head+sizelen+checksumlen
	packlen = +2 + 4 + 4;
	memcpy(&buf[2], &packlen, sizeof(packlen));
#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));

	if (pThis->CmdSendRcvProc(5, buf, packlen, recbuf, &reclen))
	{

		pThis->pFormView3->RichEditShow(5, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
	
		return ;

	}
	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
	}
	return;
}
void WINAPIV CMainFrame::RunCmdCancel6(LPVOID lParam)
{
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR buf[256 * 1024];
	UCHAR recbuf[4096];
	CString strtmp;

	UINT checksum, packlen, reclen, recchecksum;

	 
	buf[0] = 'C';
	buf[1] = 1;
	//head+sizelen+checksumlen
	packlen = +2 + 4 + 4;
	memcpy(&buf[2], &packlen, sizeof(packlen));
#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));

	if (pThis->CmdSendRcvProc(6, buf, packlen, recbuf, &reclen))
	{

		pThis->pFormView3->RichEditShow(6, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		
		return ;

	}
	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
	}
	return;
}
void WINAPIV CMainFrame::RunCmdCancel7(LPVOID lParam)
{
	int nProgIdx=7;
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR buf[256 * 1024];
	UCHAR recbuf[4096];
	CString strtmp;

	UINT checksum, packlen, reclen, recchecksum;


	buf[0] = 'C';
	buf[1] = 1;
	//head+sizelen+checksumlen
	packlen = +2 + 4 + 4;
	memcpy(&buf[2], &packlen, sizeof(packlen));
#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));

	if (pThis->CmdSendRcvProc(nProgIdx, buf, packlen, recbuf, &reclen))
	{

		pThis->pFormView3->RichEditShow(nProgIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		return;

	}
	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
	}
	return;
}
void WINAPIV CMainFrame::RunCmdCancel8(LPVOID lParam)
{
	int nProgIdx=8;
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR buf[256 * 1024];
	UCHAR recbuf[4096];
	CString strtmp;

	UINT checksum, packlen, reclen, recchecksum;


	buf[0] = 'C';
	buf[1] = 1;
	//head+sizelen+checksumlen
	packlen = +2 + 4 + 4;
	memcpy(&buf[2], &packlen, sizeof(packlen));
#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));

	if (pThis->CmdSendRcvProc(nProgIdx, buf, packlen, recbuf, &reclen))
	{

		pThis->pFormView3->RichEditShow(nProgIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
		
		return ;

	}
	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
	}
	return;
}
void WINAPIV CMainFrame::RunCmdCancel9(LPVOID lParam)
{
	
	CMainFrame *pThis = (CMainFrame *)lParam;
	UCHAR buf[256 * 1024];
	UCHAR recbuf[4096];
	CString strtmp;

	int nProgIdx = 9;
	UINT checksum, packlen, reclen, recchecksum;

	buf[0] = 'C';
	buf[1] = 1;
	//head+sizelen+checksumlen
	packlen = 2 + 4 + 4;
	memcpy(&buf[2], &packlen, sizeof(packlen));
#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));

	if (pThis->CmdSendRcvProc(nProgIdx, buf, packlen, recbuf, &reclen))
	{

		pThis->pFormView3->RichEditShow(nProgIdx, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);

		return;

	}
	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
	}
	return;
}
void  CMainFrame::Beep(int nProg,UCHAR cType)
{
	
	UCHAR buf[256 * 1024];UCHAR recbuf[4096];
	CString strtmp;

	UINT checksum, packlen, reclen, recchecksum;

	if (g_nIsBeepON)
	{
		buf[0] = 'b';
		buf[1] = cType;
		packlen = 8 + 2 + 4 + 4;
		//head+sizelen+checksumlen
		memcpy(&buf[2], &packlen, sizeof(packlen));
		memcpy(&buf[2 + 4], &stu_UsbDeviceArr[nProg].nSockProgStatus, sizeof(stu_UsbDeviceArr[nProg].nSockProgStatus));
		memcpy(&buf[2 + 4 + 4], &stu_UsbDeviceArr[nProg].curSocketUnit, sizeof(stu_UsbDeviceArr[nProg].curSocketUnit));

#ifdef ENCRYPTCHIP
		checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
		checksum = CalcCheckSum(buf, packlen - 4);
#endif
		memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));
		if (CmdSendRcvProc(nProg, buf, packlen, recbuf, &reclen))
		{
			pFormView3->RichEditShow(nProg, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
			return;
		}

		checksum = CalcCheckSum(recbuf, reclen - 4);
		memcpy(&recchecksum, &recbuf[reclen - 4], 4);
		if (checksum != recchecksum)
		{
			AfxMessageBox(L"rec checksum not match");
		}
	}
	
	return;
}
void  CMainFrame::HighZ_CloseV(int nProg)
{
#ifdef ONLINE
	if (0 == g_nAutoHigzandCloseV)return;
	if (CUSTOMERDEF_HUAJIE == g_nCustomerDef)return;
	UCHAR buf[256 * 1024]; UCHAR recbuf[4096];
	CString strtmp;

	UINT checksum, packlen, reclen, recchecksum;

	
		buf[0] = 'E';
		buf[1] = 1;
		packlen = 2 + 4 + 4;
		//head+sizelen+checksumlen
		memcpy(&buf[2], &packlen, sizeof(packlen));
#ifdef ENCRYPTCHIP
		checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
		checksum = CalcCheckSum(buf, packlen - 4);
#endif
		memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));


		if (CmdSendRcvProc(nProg, buf, packlen, recbuf, &reclen))
		{
			pFormView3->RichEditShow(nProg, L"USB cmd transfer err", COLOR_RED, CFE_BOLD, 8);
			return;
		}
		checksum = CalcCheckSum(recbuf, reclen - 4);
		memcpy(&recchecksum, &recbuf[reclen - 4], 4);
		if (checksum != recchecksum)
		{
			AfxMessageBox(L"rec checksum not match");
		}
		return;
	
#endif
	return;
}



//获得配置字的设置选项，和设置内容
//pPath 配置字路径，获得设置选项
// pSavedConfigData  设置内容
int CMainFrame::GetConfigFromFile(TCHAR *pPath,int *pSavedConfigData)
{

	BOOL bRnt = FALSE;
	int i, j;
	int nTmp1;
	CString strTmp;
	TCHAR wsztemp[20], wsztemp1[20];
	char sztemp[25];
	TCHAR chConfigFile[MAX_PATH];
	int nRealEditcnt = 0;

	wcscpy_s(chConfigFile, pPath);
	errno_t err = 0;
	if ((err = _taccess_s(chConfigFile, 0)) != 0)
	{
		return FALSE;
	}

	nTotalPages = GetPrivateProfileInt(_T("Number"), _T("nTotalPage"), 10, chConfigFile);
	if (nTotalPages > 8 && nTotalPages < 1)
	{
		return FALSE;
	}
	for (i = 0; i < nTotalPages; i++)
	{
		_stprintf(wsztemp1, _T("Page%dName"), i);
		//GetPrivateProfileString(_T("Number"), wsztemp1, _T("Page"), g_wszPageTitle[i], 49, chConfigFile);
		strTmp.LoadString(IDS_CONFIGPAGE_TITLE);
		strTmp.AppendFormat(L" %d", i + 1);
		wcscpy(g_wszPageTitle[i], strTmp.GetBuffer());
		//ConfigPageArr[i].m_psp.pszTitle = strPageTitle;


	}
	//清空下方数据结构
	memset(&g_ConfigData, 0, sizeof(g_ConfigData));
	
	//单选框
	nSingleIntCnt = GetPrivateProfileInt(_T("Number"), _T("SingleInt"), 0, chConfigFile);
	if (pConfigEditOneValue != NULL)
	{
		delete[]pConfigEditOneValue;
	}
	pConfigEditOneValue = new ConfigEditOneValue[nSingleIntCnt];
	memset(pConfigEditOneValue, 0, sizeof(ConfigEditOneValue)*(nSingleIntCnt));
	if (nSingleIntCnt > 63 && nSingleIntCnt < 0)
	{
		//		AfxMessageBox(IDS_ERRORCONFIGFILE);
		return FALSE;
	}

	//
	for (i = 0; i<nSingleIntCnt; i++)
	{
		_stprintf(wsztemp, _T("SingleInt%i"), i);
		nTmp1 = GetPrivateProfileInt(wsztemp, _T("Page"), 10, chConfigFile);
		if (nTmp1>nTotalPages && nTmp1 < 1)
		{
			//AfxMessageBox(IDS_ERRORCONFIGFILE);
			return FALSE;
		}
		pConfigEditOneValue[i].nPage = nTmp1;
		nTmp1 = GetPrivateProfileInt(wsztemp, _T("Pos"), 10, chConfigFile);
		pConfigEditOneValue[i].nPos = nTmp1;
		nTmp1 = GetPrivateProfileInt(wsztemp, _T("Type"), 0, chConfigFile);
		pConfigEditOneValue[i].cType = nTmp1;
		GetPrivateProfileString(wsztemp, _T("Name"), _T(""), pConfigEditOneValue[i].chName, 25, chConfigFile);
		GetPrivateProfileString(wsztemp, _T("Default"), _T(""), wsztemp1, 20, chConfigFile);
		TcharToChar(sztemp, wsztemp1);
		char *pEnd;
			pConfigEditOneValue[i].nValue = strtoul(sztemp, &pEnd, 16);
		//pConfigEditOneValue[i].nValue = GetPrivateProfileInt(wsztemp, _T("Default"), 0, chConfigFile);
		if (pSavedConfigData != NULL)
		{
			pConfigEditOneValue[i].nValue = pSavedConfigData[pConfigEditOneValue[i].nPos];
		}
		//下发参数赋值
		g_ConfigData.nData[pConfigEditOneValue[i].nPos] = pConfigEditOneValue[i].nValue;
		nRealEditcnt++;
		//pnNumofByte[nTmp1 - 1]++;
	}
	//CHECK &radio
	nMultiCnt = GetPrivateProfileInt(_T("Number"), _T("MultiBit"), 0, chConfigFile);
	if (pConfigBitMultiValue != NULL)
	{
		delete[]pConfigBitMultiValue;
	}
	pConfigBitMultiValue = new ConfigBitMultiValue[nMultiCnt];
	memset(pConfigBitMultiValue, 0, sizeof(ConfigBitMultiValue)*(nMultiCnt));
	if (nMultiCnt > 63 && nMultiCnt < 0)
	{
		//		AfxMessageBox(IDS_ERRORCONFIGFILE);
		return FALSE;
	}
	for (i = 0; i<nMultiCnt; i++)
	{
		_stprintf(wsztemp, _T("MultiBit%i"), i);
		nTmp1 = GetPrivateProfileInt(wsztemp, _T("Page"), 10, chConfigFile);
		if (nTmp1>nTotalPages && nTmp1 < 1)
		{
			//AfxMessageBox(IDS_ERRORCONFIGFILE);
			return FALSE;
		}
		pConfigBitMultiValue[i].nPage = nTmp1;
		nTmp1 = GetPrivateProfileInt(wsztemp, _T("Pos"), 10, chConfigFile);
		pConfigBitMultiValue[i].nPos = nTmp1;
		nTmp1 = GetPrivateProfileInt(wsztemp, _T("Type"), 10, chConfigFile);
		pConfigBitMultiValue[i].cType = nTmp1;
		GetPrivateProfileString(wsztemp, _T("Name"), _T(""), pConfigBitMultiValue[i].chName, 25, chConfigFile);
		g_ConfigData.nData[pConfigBitMultiValue[i].nPos] = pConfigBitMultiValue[i].nPos;
		nTmp1 = GetPrivateProfileInt(wsztemp, _T("Cnt"), 10, chConfigFile);
		pConfigBitMultiValue[i].nCnt = nTmp1;
		pConfigBitMultiValue[i].nValue = GetPrivateProfileInt(wsztemp, _T("Default"), 0, chConfigFile);
		if (pSavedConfigData != NULL)
		{
			pConfigBitMultiValue[i].nValue = pSavedConfigData[pConfigBitMultiValue[i].nPos];
		}
		//下发参数赋值
		g_ConfigData.nData[pConfigBitMultiValue[i].nPos] = pConfigBitMultiValue[i].nValue;
		for (j = 0; j < pConfigBitMultiValue[i].nCnt; j++)
		{
			_stprintf(wsztemp1, _T("SubName%d"), j);
			GetPrivateProfileString(wsztemp, wsztemp1, _T(""), pConfigBitMultiValue[i].chSubName[j], 25, chConfigFile);
		}
	}



	return 0;
}



int CMainFrame::GetSN_SD(int nDevNo,char *pszSN,char *pIsSD)
{
	char szSerial[49];
	TcharToChar(szSerial, stu_UsbDeviceArr[nDevNo].pUsbDevice->SerialNumber);
	memcpy(pszSN, szSerial, 16);
	pszSN[16] = 0;
	pIsSD[0] = szSerial[16];
#if LHY
/*
	int nSN = atoi(pszSN);

	if (nSN >= 40)
	{
		memset(pszSN, 0, 16);
	}*/
#endif


	return 1;
}


void CMainFrame::SetProgramerCount(int nProgCnt)
{
	TCHAR swzinipath[MAX_PATH];
	wcscpy_s(swzinipath, g_wszCurPath);
	wcscat_s(swzinipath, L"setting.ini");
	
	g_nCustomerDefProgCnt = nProgCnt;
	CString strProCnt;
	strProCnt.Format(L"%d", g_nCustomerDefProgCnt);

	WritePrivateProfileString(L"ProgInfo", L"ProgCount", strProCnt, swzinipath);
}
int CMainFrame::GetProgramerCount()
{
	TCHAR swzinipath[MAX_PATH];
	wcscpy_s(swzinipath, g_wszCurPath);
	wcscat_s(swzinipath, L"setting.ini");

	
	g_nCustomerDefProgCnt=GetPrivateProfileInt(L"ProgInfo", L"ProgCount", 1, swzinipath);
	return g_nCustomerDefProgCnt;
	
}
void CMainFrame::Updatefirmwaresingle(int nSockIdx)
{
	//	TCHAR wszTemp[MAX_PATH];
	int i = 0, ret;
	int filelen, bRet;
	TCHAR wzbuf[MAX_PATH];
	TCHAR wszFilename[50];
	CString strtmp;
	CharToTchar(wszFilename, "a.out");
	wcscpy_s(wzbuf, g_wszCurPath);
	wcscat(wzbuf, L"lib\\");
	wcscat(wzbuf, wszFilename);
	if (g_isProgramOnline)
	{
		if (AnyprogRunning(0xFF))
		{
			pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
			return;
		}


		
		HANDLE hFile;
		hFile = CreateFile(wzbuf,
			GENERIC_READ,//对文件的操作
			0, // 共享的方式 0 不能共享
			NULL,// 安全属性 用缺省的
			OPEN_EXISTING, //
			FILE_ATTRIBUTE_READONLY | FILE_SHARE_READ, // 文件属性
			NULL); // 模板文件的句柄

		if (hFile == INVALID_HANDLE_VALUE)
		{
			strtmp.Format(L"open %s fail", wzbuf);
			AfxMessageBox(strtmp);
			return;
		}
		filelen = GetFileSize(hFile, NULL);
		char *pContent = (char *)malloc(filelen);


		DWORD dwReadSize = 0;
		bRet = ReadFile(hFile, pContent, filelen, &dwReadSize, NULL);
		if (!bRet)
		{
			CloseHandle(hFile);
			strtmp.Format(L"read %s fail", wzbuf);
			AfxMessageBox(strtmp);
			free(pContent);
			return;
		}
		CloseHandle(hFile);


		i = nSockIdx;


		//升级固件
		ret = SendAlgo(i, 4, pContent, filelen);
		if (ret == 0)
		{
			pFormView3->RichEditShow(i, L"update Fmw ok\n", COLOR_YELLOW, 0, 0);
			pFormView3->RichEditShow(i, L"rebooting wait.....\n", COLOR_YELLOW, 0, 0);
		}
		else
		{
			pFormView3->RichEditShow(i, L"update Fmw Fail", COLOR_RED, 0, 0);
		}
		
		free(pContent);
	}

}

void CMainFrame::OnUpdateFirmware()
{
//	TCHAR wszTemp[MAX_PATH];
	int i = 0,ret;
	int filelen,bRet;
		TCHAR wzbuf[MAX_PATH];
		TCHAR wszFilename[50];
		CString strtmp;
		CharToTchar(wszFilename, "a.out");
		wcscpy_s(wzbuf, g_wszCurPath);
		wcscat(wzbuf, L"lib\\");
		wcscat(wzbuf, wszFilename);
		if (g_isProgramOnline)
		{
			if (AnyprogRunning(0xFF))
			{
				pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
				return;
			}




			HANDLE hFile;
			hFile = CreateFile(wzbuf,
				GENERIC_READ,//对文件的操作
				0, // 共享的方式 0 不能共享
				NULL,// 安全属性 用缺省的
				OPEN_EXISTING, //
				FILE_ATTRIBUTE_READONLY, // 文件属性
				NULL); // 模板文件的句柄

			if (hFile == INVALID_HANDLE_VALUE)
			{
				strtmp.Format(L"open %s fail", wzbuf);
				AfxMessageBox(strtmp);
				return;
			}
			filelen = GetFileSize(hFile, NULL);
			char *pContent = (char *)malloc(filelen);


			DWORD dwReadSize = 0;
			bRet = ReadFile(hFile, pContent, filelen, &dwReadSize, NULL);
			if (!bRet)
			{
				CloseHandle(hFile);
				strtmp.Format(L"read %s fail", wzbuf);
				AfxMessageBox(strtmp);
				free(pContent);
				return;
			}
			CloseHandle(hFile);

		
				for (i = 0; i < PROGRAMERMAXNUM; i++)
				{

					if (stu_UsbDeviceArr[i].status == USBCONNECT_IDLE)
					{


						//升级固件
						ret = SendAlgo(i, 4, pContent, filelen);
						if (ret == 0)
						{
							pFormView3->RichEditShow(i, L"update Fmw ok\n", COLOR_YELLOW, 0, 0);
							pFormView3->RichEditShow(i, L"rebooting wait.....\n", COLOR_YELLOW, 0, 0);
						}
						else
						{
							pFormView3->RichEditShow(i, L"update Fmw Fail", COLOR_RED, 0, 0);
						}
					}
				}
				free(pContent);
		}
		
}


void CMainFrame::OnClose()
{


	typedef void(__stdcall* quitdialog)();
	quitdialog quitdialogfunc;
	if (m_dllhandleConnectDlg)
	{

		quitdialogfunc = (quitdialog)(GetProcAddress(m_dllhandleConnectDlg, "QuitDialog"));
		quitdialogfunc();
		FreeLibrary(m_dllhandleConnectDlg);
		m_dllhandleConnectDlg = NULL;
	}

	DispSocketStatSum();
	logsumStr(L"");
	logsumStr(L"**************************");
	logsumStr(L"CLose App");
	logsumStr(L"**************************");
	logsumStr(L"");
	if(NULL!=pstuDevInfo)
	{
		free(pstuDevInfo);
	}
	CFrameWnd::OnClose();
}
afx_msg void CMainFrame::OnToolbarDropDown(NMHDR* pnmhdr, LRESULT* plRes)
{
	TCHAR swztemp[50];
	LPNMTOOLBAR pnmh = reinterpret_cast<LPNMTOOLBAR>(pnmhdr);
	CWnd *pWnd;
	UINT nID;
	INT i = 0,j=0;
	//CProgFileDialog profiledlg;
	int menuIDArray[] = { ID_MENU0_BUF0, ID_MENU0_BUF1, ID_MENU0_BUF2, ID_MENU0_BUF3, ID_MENU0_BUF4, ID_MENU0_BUF5, ID_MENU0_BUF6, ID_MENU0_BUF7, ID_MENU0_BUF8, ID_MENU0_BUF9 };
	if (g_curDeviceSel == -1)return;
	if (AnyprogRunning(0xFF))
	{
		pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED,0,0);
		return;
	}
	switch (pnmh->iItem)
	{
	case ID_MENU_FUN10:
		pWnd = &m_wndToolBar;
		nID = IDR_MENU1;
		break;
	default:
		return;
	}
	

	CMenu* pPop = cMenuDropDown.GetSubMenu(0);//加载下拉菜单
	int iItemCount = pPop->GetMenuItemCount();
	for ( i = 0; i < iItemCount; ++i)
	{
		//清除该菜单中的项
		pPop->DeleteMenu(0, MF_BYPOSITION);
	}
	for ( i = 0; i < BUFNUM; ++i)
	{
		if ((pstuDevInfo[g_curDeviceSel].cIsBufferHide[i]==0) && strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]) && strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[i]))
		{
			CharToTchar(swztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);
		//	wcscat(swztemp, L".bf");
			pPop->AppendMenuW(MF_STRING, menuIDArray[j++], swztemp);
		}
	}
	
	CRect cRect;
	pWnd->SendMessage(TB_GETRECT, pnmh->iItem, (LPARAM)&cRect);//取得下拉按钮的矩形区域
	pWnd->ClientToScreen(&cRect);//转换为屏幕坐标
	pPop->TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_VERTICAL, cRect.left, cRect.bottom, this, &cRect);//弹出菜单

}
void CMainFrame::OnMenuBufQhex(int nBufx)
{
	
	TCHAR swzname[50];
	CString path;
	CString filepath;
	CString strWorkPath ;
	path.Format(L"%slib\\", g_wszCurPath);
	//path += L"buffile0";

	//	path += wszPath;
	CMenu* pPop = cMenuDropDown.GetSubMenu(0);//加载下拉菜单
	CString strMenu;
	pPop->GetMenuStringW(nBufx, strMenu, MF_BYPOSITION);
	//	int retId = TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD, pt.x, pt.y, 0, this->m_hWnd, NULL);

	for (int i = 0; i < BUFNUM; i++)
	{
		CharToTchar(swzname, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);

		if (strMenu == swzname)
		{
			strMenu = swzname;
			strMenu += L".bf";
			break;
		}
	}
	filepath = g_wszCurPath;
	filepath += L"lib\\";
	filepath += strMenu;
	filepath += L" XC123";

	
	path += strMenu;
	strMenu.Empty();
	strMenu = g_wszCurPath;
	strMenu.AppendFormat(L"%s", L"lib\\");
	strWorkPath = strMenu;

	strMenu = g_wszCurPath;
	strMenu += _T("qhexedit.exe");


	//strMenu += path;
/*
	TCHAR* wszPath = strMenu.GetBuffer();
	char szPath[MAX_PATH];
	TcharToChar(szPath, wszPath);
	WinExec(szPath, SW_SHOW);
	strMenu.ReleaseBuffer();
	*/




	unsigned long Result=0;
	
	CString strRes;
	//strWorkPath += _T("\\netcfg\\");
	SHELLEXECUTEINFO ShExeInfo = { 0 };
	ShExeInfo.cbSize = sizeof(SHELLEXECUTEINFO);
	ShExeInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
	ShExeInfo.hwnd = NULL;
	ShExeInfo.lpVerb = NULL;
	ShExeInfo.lpFile = strMenu;
	ShExeInfo.lpParameters = filepath;
	ShExeInfo.lpDirectory = strWorkPath;
	ShExeInfo.nShow = SW_SHOWNORMAL;
	ShExeInfo.hInstApp = NULL;
	ShellExecuteEx(&ShExeInfo);
	WaitForSingleObject(ShExeInfo.hProcess, INFINITE);
	GetExitCodeProcess(ShExeInfo.hProcess, &Result);
	if (0 != Result)
	{
		
	}




}

void CMainFrame::OnMenu0Bufx(int nBufx)
{
	TCHAR swzname[50];
	CString path;
	path.Format(L"%slib\\", g_wszCurPath);
	//path += L"buffile0";

	//	path += wszPath;
	CMenu* pPop = cMenuDropDown.GetSubMenu(0);//加载下拉菜单
	CString strMenu;
	pPop->GetMenuStringW(nBufx, strMenu, MF_BYPOSITION);
	//	int retId = TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD, pt.x, pt.y, 0, this->m_hWnd, NULL);
	
	for (int i=0; i < BUFNUM; i++)
	{
			CharToTchar(swzname, pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]);
			
			if (strMenu == swzname)
			{
				strMenu = swzname;
				strMenu += L".bf";
				break;
			}		
	}
	
	path += strMenu;
	strMenu.Empty();
	strMenu = g_wszCurPath;
	strMenu.AppendFormat(L"%s", L"lib\\HxD.exe ");

	strMenu += path;

	TCHAR *wszPath = strMenu.GetBuffer();
	char szPath[MAX_PATH];
	TcharToChar(szPath, wszPath);
	WinExec(szPath, SW_SHOW);
	strMenu.ReleaseBuffer();

}
void CMainFrame::OnMenu0Buf0()
{

	//OnMenuBufQhex(0);
	OnMenu0Bufx(0);
}

void CMainFrame::OnMenu0Buf1()
{
	OnMenu0Bufx(1);
}


void CMainFrame::OnMenu0Buf2()
{
	OnMenu0Bufx(2);

}


void CMainFrame::OnMenu0Buf3()
{
	OnMenu0Bufx(3);
}


void CMainFrame::OnMenu0Buf4()
{
	OnMenu0Bufx(4);
}

void CMainFrame::OnMenu0Buf5()
{
	OnMenu0Bufx(5);
}
void CMainFrame::OnMenu0Buf6()
{
	OnMenu0Bufx(6);
}
void CMainFrame::OnMenu0Buf7()
{
	OnMenu0Bufx(7);
}
void CMainFrame::OnMenu0Buf8()
{
	OnMenu0Bufx(8);
}
void CMainFrame::OnMenu0Buf9()
{
	OnMenu0Bufx(9);
}

int CMainFrame::OnReceiveStrNet(LPBYTE lpBuffer, DWORD dwCount)
{
	return OnReceiveStrSerialNet((WPARAM)lpBuffer, (LPARAM)&dwCount);
}
int CMainFrame::DeleteOtherPrjFiles(CString strpath, CString usedFile, CString strExt)
{
	INT nDeleteCnt = 0;
	CFileFind tempFind;
	TCHAR sTempFileFind[512];

	wsprintf(sTempFileFind, L"%s*.*", strpath);
	BOOL IsFinded = tempFind.FindFile(sTempFileFind);
	while (IsFinded)
	{
		IsFinded = tempFind.FindNextFile();

		if (!tempFind.IsDots())
		{
			TCHAR sFoundFileName[512];
			wcscpy(sFoundFileName, tempFind.GetFileName().GetBuffer(200));

			if (tempFind.IsDirectory())
			{
				TCHAR sTempDir[200];
				wsprintf(sTempDir, L"%s\\%s", strpath, sFoundFileName);
			//	DeleteDirectory(sTempDir);
			}
			else
			{

		
				if (tempFind.GetFileName().Right(wcslen(strExt)) == strExt)
				{
					if (tempFind.GetFileName() != (usedFile + strExt))
					{
						DeleteFile(tempFind.GetFilePath());
						nDeleteCnt++;
					}
				}
			
			}
		}
	}
	tempFind.Close();
	
	return nDeleteCnt;
}
STU_POINT_tag* pStu_YHY16_SiteP[] = { stu_YHY16_locSite0,
	stu_YHY16_locSite1,
	stu_YHY16_locSite2,
	stu_YHY16_locSite3,
	stu_YHY16_locSite4,
	stu_YHY16_locSite5,
	stu_YHY16_locSite6,
	stu_YHY16_locSite7,
	stu_YHY16_locSite8,
	stu_YHY16_locSite9
};




LRESULT CMainFrame::OnSetBalls0(WPARAM str, LPARAM pBytes)
{
	int nProg = 0;
	int i;
	
	CMainFrame* pMainFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd;
	
	typedef void(__stdcall* settextFunc)(char*,int);
	settextFunc psettextFunc;
	typedef void(__stdcall* cahngebFunc)(int, int, char*);
	cahngebFunc pchangeFunc;
	if (50==g_nDebugValue)
	{
		if (m_dllhandleConnectDlg)
		{
			
			pchangeFunc = (cahngebFunc)(GetProcAddress(pMainFrame->m_dllhandleConnectDlg, "changeBall"));
			char* color("red");
			
			for (i = 0; i < 16; i++)
			{

				if (ucballloc[nProg][i])
				{
					pchangeFunc( pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "red");
				}
				else
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "green");
				}
				
			}
			psettextFunc = reinterpret_cast<settextFunc>(GetProcAddress(m_dllhandleConnectDlg, "setfuwenbenText"));
			psettextFunc(ucszText[nProg], nProg+1);
			
		}
	}
	return 0;
}
LRESULT CMainFrame::OnSetBalls1(WPARAM str, LPARAM pBytes) 
{
	int nProg = 1;
	int i;

	CMainFrame* pMainFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd;

	typedef void(__stdcall* settextFunc)(char*, int);
	settextFunc psettextFunc;
	typedef void(__stdcall* cahngebFunc)(int, int, char*);
	cahngebFunc pchangeFunc;
	if (50==g_nDebugValue)
	{
		if (m_dllhandleConnectDlg)
		{
			pchangeFunc = (cahngebFunc)(GetProcAddress(pMainFrame->m_dllhandleConnectDlg, "changeBall"));
			
			
			for (i = 0; i < 16; i++)
			{
				if (ucballloc[nProg][i])
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "red");
				}
				else
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "green");
				}

			}
			psettextFunc = reinterpret_cast<settextFunc>(GetProcAddress(m_dllhandleConnectDlg, "setfuwenbenText"));
			psettextFunc(ucszText[nProg], nProg + 1);
			
		}
	}
	return 0;
};
LRESULT CMainFrame::OnSetBalls2(WPARAM str, LPARAM pBytes) 
{
	int nProg = 2;
	int i;

	CMainFrame* pMainFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd;

	typedef void(__stdcall* settextFunc)(char*, int);
	settextFunc psettextFunc;
	typedef void(__stdcall* cahngebFunc)(int, int, char*);
	cahngebFunc pchangeFunc;
	if (50==g_nDebugValue)
	{
		if (m_dllhandleConnectDlg)
		{

			pchangeFunc = (cahngebFunc)(GetProcAddress(pMainFrame->m_dllhandleConnectDlg, "changeBall"));
			
			
			for (i = 0; i < 16; i++)
			{
				if (ucballloc[nProg][i])
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "red");
				}
				else
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "green");
				}

			}
			psettextFunc = reinterpret_cast<settextFunc>(GetProcAddress(m_dllhandleConnectDlg, "setfuwenbenText"));
			psettextFunc(ucszText[nProg], nProg + 1);
			
		}
	}
	return 0;
};
LRESULT CMainFrame::OnSetBalls3(WPARAM str, LPARAM pBytes) 
{
	int nProg = 3;
	int i;

	CMainFrame* pMainFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd;

	typedef void(__stdcall* settextFunc)(char*, int);
	settextFunc psettextFunc;
	typedef void(__stdcall* cahngebFunc)(int, int, char*);
	cahngebFunc pchangeFunc;
	if (50==g_nDebugValue)
	{
		if (m_dllhandleConnectDlg)
		{

			pchangeFunc = (cahngebFunc)(GetProcAddress(pMainFrame->m_dllhandleConnectDlg, "changeBall"));
			
			for (i = 0; i < 16; i++)
			{
				if (ucballloc[nProg][i])
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "red");
				}
				else
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "green");
				}

			}
			psettextFunc = reinterpret_cast<settextFunc>(GetProcAddress(m_dllhandleConnectDlg, "setfuwenbenText"));
			psettextFunc(ucszText[nProg], nProg + 1);
			
		}
	}
	return 0;
};
LRESULT CMainFrame::OnSetBalls4(WPARAM str, LPARAM pBytes) 
{
	int nProg = 4;
	int i;

	CMainFrame* pMainFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd;

	typedef void(__stdcall* settextFunc)(char*, int);
	settextFunc psettextFunc;
	typedef void(__stdcall* cahngebFunc)(int, int, char*);
	cahngebFunc pchangeFunc;
	if (50==g_nDebugValue)
	{
		if (m_dllhandleConnectDlg)
		{

			pchangeFunc = (cahngebFunc)(GetProcAddress(pMainFrame->m_dllhandleConnectDlg, "changeBall"));
			
			for (i = 0; i < 16; i++)
			{
				if (ucballloc[nProg][i])
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "red");
				}
				else
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "green");
				}

			}
			psettextFunc = reinterpret_cast<settextFunc>(GetProcAddress(m_dllhandleConnectDlg, "setfuwenbenText"));
			psettextFunc(ucszText[nProg], nProg + 1);
			
		}
	}
	return 0;
};
LRESULT CMainFrame::OnSetBalls5(WPARAM str, LPARAM pBytes) 
{
	int nProg = 5;
	int i;
	
	CMainFrame* pMainFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd;

	typedef void(__stdcall* settextFunc)(char*, int);
	settextFunc psettextFunc;
	typedef void(__stdcall* cahngebFunc)(int, int, char*);
	cahngebFunc pchangeFunc;
	if (50==g_nDebugValue)
	{
		if (m_dllhandleConnectDlg)
		{

			pchangeFunc = (cahngebFunc)(GetProcAddress(pMainFrame->m_dllhandleConnectDlg, "changeBall"));
			
			for (i = 0; i < 16; i++)
			{
				if (ucballloc[nProg][i])
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "red");
					
				}
				else
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "green");
				}

			}
			psettextFunc = reinterpret_cast<settextFunc>(GetProcAddress(m_dllhandleConnectDlg, "setfuwenbenText"));
			psettextFunc(ucszText[nProg], nProg + 1);
			
		}
	}
	return 0;
};
LRESULT CMainFrame::OnSetBalls6(WPARAM str, LPARAM pBytes) 
{
	int nProg = 6;
	int i;

	CMainFrame* pMainFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd;

	typedef void(__stdcall* settextFunc)(char*, int);
	settextFunc psettextFunc;
	typedef void(__stdcall* cahngebFunc)(int, int, char*);
	cahngebFunc pchangeFunc;
	if (50==g_nDebugValue)
	{
		if (m_dllhandleConnectDlg)
		{

			pchangeFunc = (cahngebFunc)(GetProcAddress(pMainFrame->m_dllhandleConnectDlg, "changeBall"));
			
			for (i = 0; i < 16; i++)
			{
				if (ucballloc[nProg][i])
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "red");
				}
				else
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "green");
				}

			}
			psettextFunc = reinterpret_cast<settextFunc>(GetProcAddress(m_dllhandleConnectDlg, "setfuwenbenText"));
			psettextFunc(ucszText[nProg], nProg + 1);
			
		}
	}
	return 0;
};
LRESULT CMainFrame::OnSetBalls7(WPARAM str, LPARAM pBytes) 
{
	int nProg = 7;
	int i;

	CMainFrame* pMainFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd;

	typedef void(__stdcall* settextFunc)(char*, int);
	settextFunc psettextFunc;
	typedef void(__stdcall* cahngebFunc)(int, int, char*);
	cahngebFunc pchangeFunc;
	if (50==g_nDebugValue)
	{
		if (m_dllhandleConnectDlg)
		{

			pchangeFunc = (cahngebFunc)(GetProcAddress(pMainFrame->m_dllhandleConnectDlg, "changeBall"));
			
			for (i = 0; i < 16; i++)
			{
				if (ucballloc[nProg][i])
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "red");
				}
				else
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "green");
				}

			}
			psettextFunc = reinterpret_cast<settextFunc>(GetProcAddress(m_dllhandleConnectDlg, "setfuwenbenText"));
			psettextFunc(ucszText[nProg], nProg + 1);
			
		}
	}
	return 0;
};
LRESULT CMainFrame::OnSetBalls8(WPARAM str, LPARAM pBytes) 
{
	int nProg = 8;
	int i;

	CMainFrame* pMainFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd;

	typedef void(__stdcall* settextFunc)(char*, int);
	settextFunc psettextFunc;
	typedef void(__stdcall* cahngebFunc)(int, int, char*);
	cahngebFunc pchangeFunc;
	if (50==g_nDebugValue)
	{
		if (m_dllhandleConnectDlg)
		{

			pchangeFunc = (cahngebFunc)(GetProcAddress(pMainFrame->m_dllhandleConnectDlg, "changeBall"));
			
			for (i = 0; i < 16; i++)
			{
				if (ucballloc[nProg][i])
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "red");
				}
				else
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "green");
				}

			}
			psettextFunc = reinterpret_cast<settextFunc>(GetProcAddress(m_dllhandleConnectDlg, "setfuwenbenText"));
			psettextFunc(ucszText[nProg], nProg + 1);
			
		}
	}
	return 0;
};
LRESULT CMainFrame::OnSetBalls9(WPARAM str, LPARAM pBytes) 
{
	int nProg = 9;
	int i;

	CMainFrame* pMainFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd;

	typedef void(__stdcall* settextFunc)(char*, int);
	settextFunc psettextFunc;
	typedef void(__stdcall* cahngebFunc)(int, int, char*);
	cahngebFunc pchangeFunc;
	if (50==g_nDebugValue)
	{
		if (m_dllhandleConnectDlg)
		{

			pchangeFunc = (cahngebFunc)(GetProcAddress(pMainFrame->m_dllhandleConnectDlg, "changeBall"));
			
			for (i = 0; i < 16; i++)
			{
				if (ucballloc[nProg][i])
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "red");
				}
				else
				{
					pchangeFunc(pStu_YHY16_SiteP[nProg][i].y, pStu_YHY16_SiteP[nProg][i].x, "green");
				}

			}
			psettextFunc = reinterpret_cast<settextFunc>(GetProcAddress(m_dllhandleConnectDlg, "setfuwenbenText"));
			psettextFunc(ucszText[nProg], nProg + 1);
			
		}
	}
	return 0;
};


LRESULT CMainFrame::OnOpenBallDlg(WPARAM str, LPARAM pBytes)
{
	if (50==g_nDebugValue)
	{
		if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
		{
			CWnd* hwnd = FindWindow(NULL, L"SetBalls");
			if (hwnd == NULL)
			{
				if (m_dllhandleConnectDlg)
				{
					typedef bool(*callback)(HWND, int, int, char*);
					callback show = (callback)(GetProcAddress(m_dllhandleConnectDlg, "showBalls"));

					// TODO: 在此添加控件通知处理程序代码

					HWND HD = GetSafeHwnd();
					char* color("green");
					show(HD, 29, 2, color);

					//FreeLibrary(dllHandle);
				}
			}

		}

	}
	return 0;
}
//临期提示6小时
#define ADP_DEADLINE_REPORT_INTV  (3600*6)
#if 1
//串口
LRESULT CMainFrame::OnReceiveStrSerialNet(WPARAM str, LPARAM pBytes)
{
	int nBufIdx = 0;
	int i = 0,j;
	int nRdBytes = *(int*)pBytes;
	char cProgAddr,cMode, cType;
	short wParaLen;
	char *pcBuf=(CHAR *)str;
	char cParaBuf[1024];
	char sztemp[256];
	char sztemp1[10];
	TCHAR swztemp[256];
	CString  tmpstr,tmpstr1;
	int offset = 0;
	int nGetFinsish = 0;
	int nDelCnt = 0;
	int nRet = 0;
	CString strMan, strDevice, strPackage, strISP;
	int idx = 0;															
	USHORT sLen = 0, wBufIdx = 0,wIsHex16=0,wIsFillFF=0, wMerge=0;//wMerge：hex是否追加
	int nBufOft;
	TCHAR drive[_MAX_DRIVE];
	TCHAR dir[_MAX_DIR];
	TCHAR fname[_MAX_FNAME];
	TCHAR ext[_MAX_EXT];
	USHORT wData1;
	UCHAR cAutoSeqIdx[50];
	UCHAR cVolAdjust[9];
	UINT nData1;
	
	USHORT wChanel = 0;
	CHAR  cBufferName[20];
	USHORT wMacLen = 0;
	UCHAR snzMac[256];
	
	time_t t;
	//short wBufidx = 0;
	CFile file;
	if (g_nComLog)
	{
		for (i = 0; i < nRdBytes; i++)
		{
			tmpstr.AppendFormat(L"%02x ", (UCHAR)pcBuf[i]);
		}
		tmpstr += L"\r\n";
		pFormView3->SaveSerialLog(1, tmpstr);
		tmpstr.Empty();
	}

	if (-1 == ParseRecSocketDataNetSerial((LPBYTE)str, nRdBytes, &cProgAddr, &cMode, &cType, &wParaLen, cParaBuf))
	{
		pcBuf = stu_RemoteStat.cBuf[0];
		strcpy(pcBuf, "ER");
		pcBuf[2] = 0;
		offset += strlen("ER") + 1;
		if (2 == stu_RemoteStat.nRemoteStat)
			SerialSendResp(cProgAddr, cType, pcBuf, offset);
		else if (1 == stu_RemoteStat.nRemoteStat)
			m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
		pFormView3->RichEditShowAll(0, L"Com rec checksum err", COLOR_RED, 0, 30);
		return -1;
	}

	if (cProgAddr != -1)
	{
		for (i = 0; i < 10; i++)
		{
			if (cProgAddr == m_nSiteNo[i])
			{
				cProgAddr = i;
				break;
			}
		}
	}
	
	//没找到给一个INVALID的数b
	if ((i >= 10)&&((UCHAR)cProgAddr!=0xff))
	{
		cProgAddr = 100;
	}
	memset(stu_RemoteStat.cBuf[0], 0, sizeof(stu_RemoteStat.cBuf[0]));
	//control mode
	CProgFileDialog filedlg;
	{
		switch (cType)
		{
		case 0:
			OnMenuAutoRun();
			break;
			
		case TYPE_LOADPRJ://加载工程
			memcpy(stu_RemoteStat.cBuf[0], (char *)str,sizeof(stu_RemoteStat.cBuf[0]));
			pcBuf = stu_RemoteStat.cBuf[0];
			memcpy(sztemp, cParaBuf, wParaLen);
			sztemp[wParaLen] = 0;
			CharToTchar(swztemp, sztemp);
			tmpstr.Format(L"%s", swztemp);
			nRet = PrjLoad(tmpstr, 1);
			if (-1 != nRet)
			{
				
				//芯片选择的LOG目录下的LOG路径初始化
				TCHAR wszTemp1[40];
				time_t t = time(0);
				struct tm newtime;
				localtime_s(&newtime, &t);
				//获得按照芯片选择保存LOG的文件名。工程名称+日期+时间
				wsprintf(wszTemp1, L"-%02d%02d%02d%02d%02d%02d", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday, newtime.tm_hour, newtime.tm_min, newtime.tm_sec);

				//路径中获得文件名
				tmpstr1 = tmpstr.Right(tmpstr.GetLength() - tmpstr.ReverseFind('\\') - 1);
				//删掉右边“.ycpj”
				m_strChipSel_PrjName = tmpstr1.Left(tmpstr1.GetLength() - strlen(".ycpj"));
				m_strChipSel_PrjName += wszTemp1;
				m_nChipSel_Prj = INPRJ;


				strcpy(pcBuf, "OK");
				if (2 == nRet)
				{
					pFormView3->RichEditShowAll(0, L"Load project OK in old setting", COLOR_GHOSTWHITE, CFE_BOLD, 5);
					
				}
				else
				{
					
					pFormView3->RichEditShowAll(0, L"Load project OK", COLOR_GHOSTWHITE, CFE_BOLD, 5);
				}
				pFormView3->RichEditShowAll(0, tmpstr, COLOR_GHOSTWHITE, 0, 0);
				
				_wsplitpath(tmpstr, drive, dir, fname, ext);
				tmpstr = drive;
				tmpstr += dir;
				if (g_nCustomerDef == CUSTOMERDEF_JIEXING)
				{
					nDelCnt = DeleteOtherPrjFiles(tmpstr, fname, ext);
					if (nDelCnt)
					{
						tmpstr.Format(L"Delete %d Prj Files", nDelCnt);
						pFormView3->RichEditShowAll(0, tmpstr, COLOR_YELLOW, 0, 0);
					}
				}
				pFormView1->DisplayDeviceInfoInleft();
				DispSocketStatSum();
				pFormView3->DisplayDeviceBrief();
				DisplayBufInfo();
				DispConfigWord(1);
				DispAutoSeq();
				DispGeneralSetting();
				DisplaySocketInfo(stu_ProjectHead.nCurUnitSel);
				for (i = 0; i < PROGRAMERMAXNUM; i++)
				{
					memset(stu_UsbDeviceArr[i].nSokFailCnt, 0, sizeof(stu_UsbDeviceArr[i].nSokFailCnt));
					memset(stu_UsbDeviceArr[i].nSokTotalCnt, 0, sizeof(stu_UsbDeviceArr[i].nSokTotalCnt));
					stu_UsbDeviceArr[i].nTotalFailCnt = 0;
					stu_UsbDeviceArr[i].nTotalCnt = 0;

				}
				if (50==g_nDebugValue)
				{
					::PostMessage(GetSafeHwnd(), WM_COMM_OPENBALLDLG, (WPARAM)NULL, (LPARAM)NULL);
				}
				
				
			}
			else
			{
				
				strcpy(pcBuf, "ER");
				stu_ProjectStatus.nIsInPrj = 0;
				pFormView3->RichEditShowAll(0, L"Load project err", COLOR_GHOSTWHITE, 0, 0);
				pFormView3->RichEditShowAll(0, tmpstr, COLOR_GHOSTWHITE, 0, 0);
				pFormView3->RichEditShowAll(0, STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);
			}
			
			m_bIsPrjEditable = FALSE;
			if (2==stu_RemoteStat.nRemoteStat)
				SerialSendResp(0xff, cType, pcBuf, strlen(pcBuf)+1);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(0xff, cType, pcBuf, strlen(pcBuf) + 1);

			break;
		case TYPE_DOJOB:
			if ((cProgAddr<0)||(cProgAddr>9))
			{
				pFormView3->RichEditShowAll(0, L"invalid PROGADDR", COLOR_RED, 0, 0);
				pcBuf = stu_RemoteStat.cBuf[0];
				strcpy(pcBuf, "ER");
				pcBuf[2] = 0;
				offset += strlen("ER") + 1;
				if (2 == stu_RemoteStat.nRemoteStat)
					SerialSendResp(cProgAddr, cType, pcBuf, offset);
				else if (1 == stu_RemoteStat.nRemoteStat)
					m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
				break;
			}
			//掉线
			else if (g_SerialResBuf[m_nSiteNo[cProgAddr] - 1] == SER_PROG_NOTCONNECT)
			{
				tmpstr.Format(L"Site%d disconnect,remote err", m_nSiteNo[cProgAddr]);
				pFormView3->RichEditShowAll(0, tmpstr, COLOR_RED, 0, 30);
				pcBuf = stu_RemoteStat.cBuf[0];
				strcpy(pcBuf, "ER");
				pcBuf[2] = 0;
				offset += strlen("ER") + 1;
				if (2 == stu_RemoteStat.nRemoteStat)
					SerialSendResp(cProgAddr, cType, pcBuf, offset);
				else if (1 == stu_RemoteStat.nRemoteStat)
					m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
				break;
			}
			
			switch ((UCHAR)cParaBuf[0])
			{
				case 0:
					

					if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
					{
						memset(&g_SerialResBuf[32 + (m_nSiteNo[cProgAddr] - 1) * 16], 0, 16);
					}
					else
					{
						memset(&g_SerialResBuf[32 + (m_nSiteNo[cProgAddr] - 1) * SOCKETMAX], 0, 8);
					}
					if (g_SerialResBuf[m_nSiteNo[cProgAddr] - 1] == SER_PROG_READY)
					{
						/*
						if (0 == AutoRunSingle(cProgAddr))
						{
							//不能写道这里，运行到这里的时候，mapX已经运行了，下面又会清掉
							g_SerialResBuf[m_nSiteNo[cProgAddr] - 1] = 0;
							memset(&g_SerialResBuf[32 + (m_nSiteNo[i] - 1) * 32], 0, 8);
						}
						*/
					
					//	g_SerialResBuf[m_nSiteNo[cProgAddr] - 1] = SER_PROG_NOTCONNECT;
#ifndef ONLINE
						time_t start_t= time(NULL);
						float tinterval;
					//	pFormView3->RichEditShow(0, tmpstr, COLOR_RED, 0, 30);

						if (stu_AdptNearLmtDlgTime.nAutoCnt == 0)
							{
								if (g_pDlgSktNearLmt == NULL)
								{
									CRect rect;
									GetClientRect(&rect);
									g_pDlgSktNearLmt = new CDialogSktNearLmt();
									g_pDlgSktNearLmt->m_strMsg = tmpstr;
									g_pDlgSktNearLmt->Create(IDD_DIALOGSKTNEARLIMIT, this);
									tmpstr.LoadStringW(IDS_STRING141);
									g_pDlgSktNearLmt->SetWindowTextW(tmpstr);
									g_pDlgSktNearLmt->ShowWindow(SW_HIDE);
								}
							}
						//if ((0 == stu_AdptNearLmtDlgTime.nHour)||(st.wHour!= stu_AdptNearLmtDlgTime.nHour))
						//if ((0 == stu_AdptNearLmtDlgTime.nHour) || (st.wMinute != stu_AdptNearLmtDlgTime.nHour))
						//第二次弹框，到时间间隔6小时弹框
						if ((2 == stu_AdptNearLmtDlgTime.nAutoCnt) || (difftime(start_t, stu_AdptNearLmtDlgTime.nHour) > ADP_DEADLINE_REPORT_INTV))
						{
							//开始创建一下，然后HIDE，之后确认其实是HIDE
							
							if (stu_AdptNearLmtDlgTime.nAutoCnt > 1)
							{
								tmpstr.Empty();
								for (i = 0; i < PROGRAMERMAXNUM; i++)
								{
									if (wcslen(m_strSktNearLmt[i]))
									{
										tmpstr += m_strSktNearLmt[i];
									
									}

								}
							
								if (0 == tmpstr.IsEmpty())
								{
									
									//else
									{
										g_pDlgSktNearLmt->m_EditMsg.SetWindowTextW(tmpstr);
										if (0 == g_pDlgSktNearLmt->IsWindowVisible())
										{
											
											g_pDlgSktNearLmt->ShowWindow(SW_SHOW);
										}
										
										//刷新信息
										
									}
								}
								stu_AdptNearLmtDlgTime.nHour = time(NULL);
								//stu_AdptNearLmtDlgTime.nHour = st.wMinute;
							}
							
							
						}
						stu_AdptNearLmtDlgTime.nAutoCnt++;
#endif
						AutoRunSingle(cProgAddr);
						
						
					}
					break;
				case 0xff:
					CancelSingle(cProgAddr);
					break;
			//	default://其他都是功能项
				//	pFormView1->RunBtnProc((1<<cProgAddr), cParaBuf[0]-1);
				//	break;

			}
			pcBuf = stu_RemoteStat.cBuf[0];
			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
		case TYPE_GETPROJINFO:
			
			pcBuf = stu_RemoteStat.cBuf[0];
			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			strcpy(pcBuf + offset, pstuDevInfo[g_curDeviceSel].szManufacture);//厂商
			offset += strlen(pstuDevInfo[g_curDeviceSel].szManufacture) + 1;
			strcpy(pcBuf + offset, pstuDevInfo[g_curDeviceSel].szDeviceName);//型号
			offset += strlen(pstuDevInfo[g_curDeviceSel].szDeviceName) + 1;
			strcpy(pcBuf + offset, pstuDevInfo[g_curDeviceSel].szPackage);//封装
			offset += strlen(pstuDevInfo[g_curDeviceSel].szPackage) + 1;
			strcpy(pcBuf + offset, pstuDevInfo[g_curDeviceSel].szAlgo);//算法
			offset += strlen(pstuDevInfo[g_curDeviceSel].szAlgo) + 1;
			memcpy(pcBuf + offset, &stu_ProjectHead.llCheckSumFile[0], 4);
			offset += 4;
			memcpy(pcBuf + offset, &stu_ProjectHead.llCheckSumBuf[0], 4);
			offset += 4;
			memcpy(pcBuf + offset, &stu_FuncList.nAutoCnt, 4);
			offset += 4;
			for (i = 0; i < stu_FuncList.nAutoCnt; i++)
			{
				strcpy(pcBuf + offset, stu_FuncList.szFunListArr[i]);//功能项
				offset += strlen(stu_FuncList.szFunListArr[i]) + 1;
			}
		
		
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(0xff, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(0xff, cType, pcBuf, offset);

			break;
			//设置SOCKET使能掩码
		case TYPE_SETADAPTEN:
			if ((cProgAddr<0) || (cProgAddr>9))
			{

				pFormView3->RichEditShowAll(0, L"invalid PROGADDR", COLOR_RED, 0, 0);
				pcBuf = stu_RemoteStat.cBuf[0];
				strcpy(pcBuf, "ER");
				pcBuf[2] = 0;
				offset += strlen("ER") + 1;
				if (2 == stu_RemoteStat.nRemoteStat)
					SerialSendResp(cProgAddr, cType, pcBuf, offset);
				else if (1 == stu_RemoteStat.nRemoteStat)
					m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
				return -1;
			}
			 int nSocketMask;
			 memcpy(&nSocketMask, cParaBuf, sizeof(nSocketMask));
			pFormView2->PlaneSktChkSet(cProgAddr, nSocketMask);

			memcpy(stu_RemoteStat.cBuf[cProgAddr], (char *)str, sizeof(stu_RemoteStat.cBuf[cProgAddr]));
			pcBuf = stu_RemoteStat.cBuf[cProgAddr];
			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
		case TYPE_GETADAPTEN:
			if (-1== g_curDeviceSel)
			{
				pFormView3->RichEditShowAll(0, L"No Device", COLOR_RED, 0, 0);
				pcBuf = stu_RemoteStat.cBuf[0];
				strcpy(pcBuf, "ER");
				pcBuf[2] = 0;
				offset += strlen("ER") + 1;
				if (2 == stu_RemoteStat.nRemoteStat)
					SerialSendResp(0xff, cType, pcBuf, offset);
				else if (1 == stu_RemoteStat.nRemoteStat)
					m_SocketObject.SendResp(0xff, cType, pcBuf, offset);
				break;
			}
			if ((cProgAddr<0) || (cProgAddr>9))
			{
				pFormView3->RichEditShowAll(0, L"invalid PROGADDR", COLOR_RED, 0, 0);
				pcBuf = stu_RemoteStat.cBuf[0];
				strcpy(pcBuf, "ER");
				pcBuf[2] = 0;
				offset += strlen(pcBuf) + 1;
				if (2 == stu_RemoteStat.nRemoteStat)
					SerialSendResp(cProgAddr, cType, pcBuf, offset);
				else if (1 == stu_RemoteStat.nRemoteStat)
					m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
				return -1;
			}
			//int nSocketMask;
			//memcpy(&nSocketMask, cParaBuf + 3, 4);
		//	pFormView2->PlaneSktChkSet(cProgAddr, nSocketMask);
			memcpy(stu_RemoteStat.cBuf[cProgAddr], (char *)str, sizeof(stu_RemoteStat.cBuf[cProgAddr]));
			pcBuf = stu_RemoteStat.cBuf[cProgAddr];
			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			memcpy(pcBuf + offset, &pstuDevInfo[g_curDeviceSel].unit, sizeof(pstuDevInfo[g_curDeviceSel].unit));
			pcBuf[offset] = pstuDevInfo[g_curDeviceSel].unit;
			offset += 4;
			memcpy(pcBuf + offset, &stu_UsbDeviceArr[cProgAddr].curSocketUnit, sizeof(stu_UsbDeviceArr[cProgAddr].curSocketUnit));
			offset += 4;
			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
		case TYPE_GETSOCKETSTATUS:
			pcBuf = stu_RemoteStat.cBuf[0];
			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
			{
				memcpy(pcBuf + offset, g_SerialResBuf + SERSOCKBASE, 32 * 16);
				offset += 32 * 16;
			}
			else
			{
				memcpy(pcBuf + offset, g_SerialResBuf + SERSOCKBASE, 32 * 8);
				offset += 32 * 8;
			}
				
			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
		case TYPE_CLRSTATUS:
#if 0
			if ((cProgAddr < 0) || (cProgAddr>7))
			{
				pFormView3->RichEditShow(0, L"invalid PROGADDR", COLOR_RED, 0, 0);
				pcBuf = stu_RemoteStat.cBuf[0];
				strcpy(pcBuf, "ER");
				pcBuf[2] = 0;
				offset += strlen(pcBuf) + 1;
				if (2 == stu_RemoteStat.nRemoteStat)
					SerialSendResp(cProgAddr, cType, pcBuf, offset);
				else if (1 == stu_RemoteStat.nRemoteStat)
					m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
				return -1;
			}
		//	g_SerialResBuf[m_nSiteNo[cProgAddr] - 1] = 0;
			//memset(&g_SerialResBuf[SERSOCKBASE + (m_nSiteNo[cProgAddr] - 1) * 8], 0, 8);
			//只把进度条清空
			g_SerialResBuf[SERPROGRESSBASE+m_nSiteNo[cProgAddr] - 1] = 0;

			pcBuf = stu_RemoteStat.cBuf[0];
			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			memcpy(pcBuf + offset, &nGetFinsish, sizeof(nGetFinsish));
			offset +=4;
			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
#endif
			//暂时兼容黄州GO CONFIRM
			memcpy(&nGetFinsish, cParaBuf, sizeof(nGetFinsish));
			for (i = 0; i < 32; i++)
			{
				if (nGetFinsish&(1 << (m_nSiteNo[i] - 1)))
				{
					//在FINISH状态才会迁移状态
					if (g_SerialResBuf[m_nSiteNo[i] - 1] == SER_PROG_FINISH)
					{
						g_SerialResBuf[m_nSiteNo[i] - 1] = SER_PROG_READY;
					}
					else
					{
						nGetFinsish &= (~(1 << (m_nSiteNo[i] - 1)));
					}

				}
			}

			pcBuf = stu_RemoteStat.cBuf[0];
			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			memcpy(pcBuf + offset, &nGetFinsish, sizeof(nGetFinsish));
			offset += 4;
			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			SerialSendResp(cProgAddr, cType, pcBuf, offset);
			break;
		case TYPE_GETPROGERMERSTTUS:
			pcBuf = stu_RemoteStat.cBuf[0];

			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			memcpy(pcBuf + offset, g_SerialResBuf, SERSOCKBASE);
			offset += SERSOCKBASE;
			if ((g_curDeviceSel != -1) && (pstuDevInfo[g_curDeviceSel].unit == 16))
				memcpy(pcBuf + offset, g_SerialResBuf + SERSOCKBASE + 16 * 32, SERSOCKBASE);
			else
				memcpy(pcBuf + offset, g_SerialResBuf + SERSOCKBASE+8*32, SERSOCKBASE);
			offset += SERSOCKBASE;
			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
		case TYPE_GETSITENO:
			pcBuf = stu_RemoteStat.cBuf[0];

			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			
			pcBuf[offset++] = m_nSiteNo[0];
			pcBuf[offset++] = m_nSiteNo[1];
			pcBuf[offset++] = m_nSiteNo[2];
			pcBuf[offset++] = m_nSiteNo[3];
			pcBuf[offset++] = m_nSiteNo[4];
			pcBuf[offset++] = m_nSiteNo[5];
			pcBuf[offset++] = m_nSiteNo[6];
			pcBuf[offset++] = m_nSiteNo[7];
			pcBuf[offset++] = m_nSiteNo[8];
			pcBuf[offset++] = m_nSiteNo[9];
			
			offset += SERSOCKBASE-10;
			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
			
		case TYPE_EDITCONFIG:
			short configcnt;
			int configidx;
			int configvalue;
			memcpy(&configcnt, cParaBuf, 2);
			for (i = 0; i < configcnt; i++)
			{
				memcpy(&configidx, cParaBuf + 2 + i * 8, sizeof(configidx));
				memcpy(&configvalue, cParaBuf + 2 + i * 8+4, sizeof(configvalue));
				g_ConfigData.nData[configidx] = configvalue;
				for (j = 0; j < nSingleIntCnt; j++)
				{
					if (pConfigEditOneValue[j].nPos == configidx)
					{
						pConfigEditOneValue[j].nValue = configvalue;
						tmpstr.Format(L"config%d=%x", j, configvalue);
						pFormView3->RichEditShowAll(0, tmpstr, COLOR_GHOSTWHITE, 0, 0);
					}
				}
				for (j = 0; j < nMultiCnt; j++)
				{
					 if (pConfigBitMultiValue[j].nPos == configidx)
					{
						pConfigBitMultiValue[j].nValue = configvalue;
						tmpstr.Format(L"config%d=%x", j, configvalue);
						pFormView3->RichEditShowAll(0, tmpstr, COLOR_GHOSTWHITE, 0, 0);
					}

				}

			}
			
			pcBuf = stu_RemoteStat.cBuf[0];
			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			
			
			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			SerialSendResp(cProgAddr, cType, pcBuf, offset);
			break;

		case TYPE_DEVICESEL://选芯片
			memcpy(stu_RemoteStat.cBuf[0], (char *)str, sizeof(stu_RemoteStat.cBuf[0]));
			pcBuf = stu_RemoteStat.cBuf[0];

			 idx = 0;
			 memcpy(&sLen, cParaBuf + idx, sizeof(sLen));
			 idx += sizeof(sLen);
			 
			 memset(sztemp, 0, sizeof(sztemp));
			strncpy(sztemp, cParaBuf + idx,sLen); idx += sLen;
			CharToTchar(swztemp, sztemp); strMan = swztemp;
			
			memcpy(&sLen, cParaBuf + idx, sizeof(sLen));
			
			idx += sizeof(sLen);
			memset(sztemp, 0, sizeof(sztemp));
			strncpy(sztemp, cParaBuf + idx, sLen); idx += sLen;
			CharToTchar(swztemp, sztemp); strDevice = swztemp;

			memcpy(&sLen, cParaBuf + idx, sizeof(sLen));
			idx += sizeof(sLen);
			memset(sztemp, 0, sizeof(sztemp));
			strncpy(sztemp, cParaBuf + idx, sLen); idx += sLen;
			CharToTchar(swztemp, sztemp); strPackage = swztemp;

			memset(sztemp, 0, sizeof(sztemp));
			sztemp[0] = cParaBuf[idx];
			CharToTchar(swztemp, sztemp); strISP= swztemp;
			idx++;		
			nRet=SelectDevice(1, strMan, strDevice, strPackage, strISP);
			if (nRet == 0)
			{
				
				pcBuf = stu_RemoteStat.cBuf[0];
				strcpy(pcBuf, "OK");
				offset += strlen("OK") + 1;
				if (2 == stu_RemoteStat.nRemoteStat)
					SerialSendResp(0xff, cType, pcBuf, offset);
				else if (1 == stu_RemoteStat.nRemoteStat)
					m_SocketObject.SendResp(0xff, cType, pcBuf, offset);
				
			}
			else
			{
				pFormView3->RichEditShowAll(0, L"Device select error", COLOR_RED, 0, 0);
				pcBuf = stu_RemoteStat.cBuf[0];
				strcpy(pcBuf, "ER");
				offset += strlen("ER") + 1;
				if (2 == stu_RemoteStat.nRemoteStat)
					SerialSendResp(0xff, cType, pcBuf, offset);
				else if (1 == stu_RemoteStat.nRemoteStat)
					m_SocketObject.SendResp(0xff, cType, pcBuf, offset);
			}
			break;

		case TYPE_LOADBINARYFILE:

			memcpy(filedlg.m_cComboBufSelMap, m_cComboBufSelMap, sizeof(m_cComboBufSelMap));
			memcpy(stu_RemoteStat.cBuf[0], (char *)str, sizeof(stu_RemoteStat.cBuf[0]));
			pcBuf = stu_RemoteStat.cBuf[0];

			//path len 2字节
			idx = 0;
			memcpy(&sLen,cParaBuf + idx, sizeof(sLen));
			idx += sizeof(sLen);
			
			//filepath
			memset(sztemp, 0, sizeof(sztemp));
			strncpy(sztemp, cParaBuf + idx, sLen); idx += sLen;
			CharToTchar(swztemp, sztemp); strMan = swztemp;
			filedlg.m_strFilePath = swztemp;

			//BUFIDX 2字节
			memcpy(&wBufIdx, cParaBuf + idx, sizeof(wBufIdx));
			idx += sizeof(wBufIdx);

			//BUF偏移量 4字节
			memcpy(&nBufOft, cParaBuf + idx, sizeof(nBufOft));
			idx += sizeof(nBufOft);

		
			filedlg.m_strShow = filedlg.m_strFilePath;
			if (0 == filedlg.LoadBinaryFileRemote(filedlg.m_strFilePath, wBufIdx, nBufOft,0))
			{
				nBufIdx = wBufIdx;

				//更新BUF中的文件，checksum,path		
				llCheckSumFile[nBufIdx] = filedlg.llCheckSumFile;
				llCheckSumBuf[nBufIdx] = filedlg.llCheckSumBuf;
				pFormView2->DispEachBufListCtrl(nBufIdx, filedlg.llCheckSumFile, filedlg.llCheckSumBuf);
				pFormView2->DispAllBufListChecksum();

				wsprintf(swztemp, L"Checksum:0X%08x", filedlg.llCheckSumFile);
				wcscat(swztemp, L"(");
				wsprintf(swztemp + wcslen(swztemp), L"0X%08x", filedlg.llCheckSumBuf);
				wcscat(swztemp, L")");
				_tcsupr(swztemp);
				pFormView3->RichEditShow(0, filedlg.m_strFilePath, COLOR_GHOSTWHITE, 0, 0);

				pFormView3->RichEditShow(0, swztemp, COLOR_GHOSTWHITE, 0, 0);
				//fill value

			
				tmpstr.Format(L"Buff Address Offset:0x%x", nBufOft);
				pFormView3->RichEditShowAll(0, tmpstr, COLOR_GHOSTWHITE, 0, 0);

				pFormView3->RichEditShowAll(0, L"Remote LoadFile ok", COLOR_GHOSTWHITE, 0, 0);
				pFormView3->RichEditShowAll(0, STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);



				//m_nIsDataLoaded = 1;
				pFormView3->RichEditShowAll(0, L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);
				pFormView3->RichEditShowAll(0, L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);

				pcBuf = stu_RemoteStat.cBuf[0];

				strcpy(pcBuf, "OK");
				offset += strlen("OK") + 1;
			}
			else
			{
				strcpy(pcBuf, "ER");
				offset += strlen("ER") + 1;
			}

						
			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break; 
		case TYPE_SETTINGKEY:
			memcpy(stu_RemoteStat.cBuf[0], (char *)str, sizeof(stu_RemoteStat.cBuf[0]));
			pcBuf = stu_RemoteStat.cBuf[0];
			//KEY组序号
			idx = 0;
			memcpy(&wData1, cParaBuf + idx, sizeof(wData1));
			idx += 2;
			//KEY 地址
			memcpy(&nData1, cParaBuf + idx, sizeof(nData1));
			idx += 4;
			//key path长度
			memcpy(&sLen, cParaBuf + idx, sizeof(sLen));
			idx +=2;
			memcpy(sztemp, cParaBuf + idx, sLen);
			sztemp[sLen] = 0;
			CharToTchar(swztemp, sztemp);
			tmpstr = swztemp;
			if (L"\\" != tmpstr.Right(1))
			{
				tmpstr += L"\\";
			}

			while (1)
			{
				if (g_curDeviceSel == -1)
				{
					nRet = 1;
					break;
				}
				else if (pstuDevInfo[g_curDeviceSel].nIsKeyAvailable == 0)
				{
					nRet = 1;
					break;
				}
				else if (wData1 > stu_GenSetting.nCnt)
				{
					//序号不对
					nRet = 2;
					break;
				}
				int len = GetKeyInDirLen(tmpstr);
				if (-1 == len)
				{
					//key 路径文件长度不统一
					nRet = 3;
					break;
				}
				
				//新的KEY。KEY cnt+1
				if (wData1 == stu_GenSetting.nCnt)
				{
					stu_GenSetting.nCnt++;
				}
				stu_GenSetting.llAddr[wData1] = nData1;
				strcpy(stu_GenSetting.szPath[wData1], sztemp);
				stu_GenSetting.nUserSnLen[wData1] = len;
				break;
			}
			if (0 == nRet)
			{
				pFormView1->DisplayDeviceInfoInleft();
				if (stu_GenSetting.nCnt)
				{
					for (i = 0; i < stu_GenSetting.nCnt; i++)
					{
						
						tmpstr.Format(L"Key%d,Addr=0x%08x", i, stu_GenSetting.llAddr[i]);
						pFormView3->RichEditShowAll(0,tmpstr, COLOR_GHOSTWHITE, CFE_BOLD, 0);
						CharToTchar(swztemp, (const char *)stu_GenSetting.szPath[i]);
						tmpstr.Format(L"Path=%s", swztemp);
						pFormView3->RichEditShowAll(0,tmpstr, COLOR_GHOSTWHITE, CFE_BOLD, 0);
					}


				}
				pFormView2->DispAllKeyListCtrl();
				strcpy(pcBuf, "OK");
				offset += strlen("OK") + 1;
			}
			else
			{
				strcpy(pcBuf, "ER");	
				sprintf(pcBuf + strlen(pcBuf), "%d", nRet);
				offset += strlen("ER") + 1;
			}
			//if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
			
		case TYPE_SENDBRDSN:
			memcpy(stu_RemoteStat.cBuf[0], (char *)str, sizeof(stu_RemoteStat.cBuf[0]));
			pcBuf = stu_RemoteStat.cBuf[0];
			//KEY组序号
			idx = 0;
			for (i = 0; i < 4; i++)
			{
				memcpy(m_szHuaJiBoardSN[i], cParaBuf + idx, 16);
				
				idx += 16;
			}
			 t = time(0);
			 struct tm newtime;
			 localtime_s(&newtime, &t);
			 wcsftime(swztemp, sizeof(swztemp), L"%X", &newtime);

		
			
			//时间
			tmpstr.Format(L"%s", swztemp);
			tmpstr.Remove(L':');
			//日期
			wsprintf(dir, L"%02d%02d%02d", (1900 + newtime.tm_year) % 2000, newtime.tm_mon + 1, newtime.tm_mday);
			//日期在前
			wcscpy_s(swztemp, dir);
			//时间在后
			wcscat(swztemp, tmpstr.GetBuffer());
			tmpstr.ReleaseBuffer();
			wcscpy_s(m_wszHuaJiBoardTime, swztemp);

			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
		

		case TYPE_EDITAUTO:
			memcpy(stu_RemoteStat.cBuf[0], (char *)str, sizeof(stu_RemoteStat.cBuf[0]));
			pcBuf = stu_RemoteStat.cBuf[0];
			//AUTO CNT
			idx = 0;
			memcpy(&wData1, cParaBuf + idx, sizeof(wData1));
			idx += 2;
			//AUTO INDEX char
			if (wData1 > sizeof(cAutoSeqIdx))
			{
				wData1 = sizeof(cAutoSeqIdx);
			}

			memset(cAutoSeqIdx, 0, sizeof(cAutoSeqIdx));
			memset(swztemp, 0, sizeof(swztemp));
			memcpy(cAutoSeqIdx, cParaBuf + idx, wData1);
			memset(sztemp1, 0, sizeof(sztemp1));
			memset(sztemp, 0, sizeof(sztemp));

			//赋值
			stu_AutoSeqGlob.nCurAutoIdx = 0;
			stu_AutoSeqGlob.nAutoCnt=wData1;
			
		/*	for (j = 0; j < 0; j++)
			{
				
				sprintf(sztemp1, "%x", );
				strcat_s(sztemp, sztemp1);
			}*/

			for (j = 0; j < stu_AutoSeqGlob.nAutoCnt; j++)
			{
				stu_AutoSeqGlob.nAutoidxArray[j] = cAutoSeqIdx[j];
				if (0 == j)wcscpy(swztemp, L"Remote Setting Auto:");
				else wcscat(swztemp, L"->");
				CharToTchar(swztemp + wcslen(swztemp), stu_FuncList.szFunListArr[cAutoSeqIdx[j]]);

			}


			//CharToTchar(swztemp, sztemp);
			//tmpstr.Format()
			pFormView3->RichEditShowAll(0, swztemp, COLOR_GHOSTWHITE, CFE_BOLD, 0);
			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;

			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
		case TYPE_VOLADJUST:
			memcpy(stu_RemoteStat.cBuf[0], (char *)str, sizeof(stu_RemoteStat.cBuf[0]));
			pcBuf = stu_RemoteStat.cBuf[0];
			//AUTO CNT
			idx = 0;
			memcpy(cVolAdjust, cParaBuf + idx, sizeof(cVolAdjust));
			for (j = 0; j < sizeof(m_szVCC) / sizeof(m_szVCC[0]); j++)
			{
				sprintf_s(m_szVCC[j], "%u", cVolAdjust[j]);
			}

			for (; j < 6 + sizeof(m_szVIO) / sizeof(m_szVIO[0]); j++)
			{
				sprintf_s(m_szVIO[j-6], "%u", cVolAdjust[j]);
			}
			
			tmpstr= L"Remote Vol Setting:";
			pFormView3->RichEditShowAll(0, tmpstr, COLOR_GHOSTWHITE, CFE_BOLD, 0);
			tmpstr.Format(L"VCC1=%u,VCC2=%u,VCC3=%u",atoi(m_szVCC[0]), atoi(m_szVCC[1]), atoi(m_szVCC[2]));
			pFormView3->RichEditShowAll(0, tmpstr, COLOR_GHOSTWHITE, CFE_BOLD, 0);
			tmpstr.Format(L"VCC3=%u,VCC4=%u,VCC5=%u", atoi(m_szVCC[3]), atoi(m_szVCC[4]), atoi(m_szVCC[5]));
			pFormView3->RichEditShowAll(0, tmpstr, COLOR_GHOSTWHITE, CFE_BOLD, 0);
			tmpstr.Format(L"VIO1=%u,VIO2=%u,VIO3=%u", atoi(m_szVIO[0]), atoi(m_szVIO[1]), atoi(m_szVIO[2]));
			pFormView3->RichEditShowAll(0, tmpstr, COLOR_GHOSTWHITE, CFE_BOLD, 0);


			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;

			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
		case TYPE_MACSEND:
			memcpy(stu_RemoteStat.cBuf[0], (char *)str, sizeof(stu_RemoteStat.cBuf[0]));
			pcBuf = stu_RemoteStat.cBuf[0];
			//几组
	
			idx = 0;
			//BUFFERNAME
			memcpy(&cBufferName, cParaBuf + idx, 20);
			CharToTchar(swztemp, cBufferName);
			idx += 20;
			//channel count
			memcpy(&wChanel, cParaBuf + idx, sizeof(wChanel));
			idx += 2;
			for (i = 0; i < wChanel; i++)
			{
				memcpy(&wMacLen, cParaBuf + idx, 2);
				idx += 2;
				memcpy(snzMac, cParaBuf + idx, wMacLen);
				snzMac[wMacLen] = 0;
				idx += wMacLen;
			}
			tmpstr = g_wszCurPath;
			tmpstr += L"lib\\";
			tmpstr += swztemp;
			nRet = file.Open(tmpstr, CFile::modeWrite);
			if (nRet == FALSE)
			{
				strcpy(pcBuf, "ER");
				offset += strlen("ER") + 1;
			}
			else
			{
				file.Write(cParaBuf+20, idx-20);
				file.Close();
				strcpy(pcBuf, "OK");
				offset += strlen("OK") + 1;
			}
		

			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
		case TYPE_GETTOTALCHECKSUM:
			pcBuf = stu_RemoteStat.cBuf[0];

			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;

			memcpy(pcBuf+offset, &llTotalCheckSumFile, sizeof(INT));
			offset += sizeof(INT);
			memcpy(pcBuf + offset, &llTotalCheckSumBuf, sizeof(INT));
			offset += sizeof(INT);
				
			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;

		case TYPE_GETBUFFERBASEADDR:
			memcpy(stu_RemoteStat.cBuf[0], (char*)str, sizeof(stu_RemoteStat.cBuf[0]));
			pcBuf = stu_RemoteStat.cBuf[0];
			//BUFFER IDX
			memcpy(&wBufIdx, cParaBuf, sizeof(wBufIdx));
			

			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			//buf出错
			if (-1 == g_curDeviceSel)
			{
				nData1 = 0xffffffff;
			}
			else if (wBufIdx > BUFNUM-1)
			{
				nData1 = 0xffffffff;
				
			}
			else if (0==(pstuDevInfo[g_curDeviceSel].wBaseAddrEn & (1 <<(wBufIdx))))
			{
				//BUFFERBASEADDR没有使能
				nData1 = 0xffffffff;
				
			}
			else
			{
				nData1 = pstuDevInfo[g_curDeviceSel].nBufBaseAddr[wBufIdx];
				
			}
			//nData1 = 0x12345678;
			memcpy(pcBuf + offset, &nData1, sizeof(INT));
			
			offset += sizeof(INT);

			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;

		case TYPE_LOADHEXFILE:

			memcpy(filedlg.m_cComboBufSelMap, m_cComboBufSelMap, sizeof(m_cComboBufSelMap));
			memcpy(stu_RemoteStat.cBuf[0], (char*)str, sizeof(stu_RemoteStat.cBuf[0]));
			pcBuf = stu_RemoteStat.cBuf[0];

			//path len 2字节
			idx = 0;
			memcpy(&sLen, cParaBuf + idx, sizeof(sLen));
			idx += sizeof(sLen);

			//filepath
			memset(sztemp, 0, sizeof(sztemp));
			strncpy(sztemp, cParaBuf + idx, sLen); idx += sLen;
			CharToTchar(swztemp, sztemp); strMan = swztemp;
			filedlg.m_strFilePath = swztemp;

			//BUFIDX 2字节
			memcpy(&wBufIdx, cParaBuf + idx, sizeof(wBufIdx));
			idx += sizeof(wBufIdx);

			//BUF偏移量 4字节
			memcpy(&nBufOft, cParaBuf + idx, sizeof(nBufOft));
			idx += sizeof(nBufOft);

			//wIsHex16 2字节
			memcpy(&wIsHex16, cParaBuf + idx, sizeof(wIsHex16));
			idx += sizeof(wIsHex16);

			//wIsFillFF 2字节
			memcpy(&wIsFillFF, cParaBuf + idx, sizeof(wIsFillFF));
			idx += sizeof(wIsFillFF);

			//wMerge 2字节
			memcpy(&wMerge, cParaBuf + idx, sizeof(wMerge));
			idx += sizeof(wMerge);

			if (0 == filedlg.LoadHexFileRemote(filedlg.m_strFilePath, wBufIdx, nBufOft, wIsHex16, wIsFillFF, wMerge))
			{
				nBufIdx = wBufIdx;

				//更新BUF中的文件，checksum,path		

				llCheckSumFile[nBufIdx] = filedlg.llCheckSumFile;
				llCheckSumBuf[nBufIdx] = filedlg.llCheckSumBuf;
				pFormView2->DispEachBufListCtrl(nBufIdx, filedlg.llCheckSumFile, filedlg.llCheckSumBuf);
				pFormView2->DispAllBufListChecksum();

				wsprintf(swztemp, L"Checksum:0X%08x", filedlg.llCheckSumFile);
				wcscat(swztemp, L"(");
				wsprintf(swztemp + wcslen(swztemp), L"0X%08x", filedlg.llCheckSumBuf);
				wcscat(swztemp, L")");
				_tcsupr(swztemp);
				pFormView3->RichEditShow(0, filedlg.m_strFilePath, COLOR_GHOSTWHITE, 0, 0);

				pFormView3->RichEditShow(0, swztemp, COLOR_GHOSTWHITE, 0, 0);
				//fill value

			
				tmpstr.Format(L"Buff Address Offset:0x%x", nBufOft);
				pFormView3->RichEditShowAll(0, tmpstr, COLOR_GHOSTWHITE, 0, 0);

				pFormView3->RichEditShowAll(0, L"Remote LoadFile ok", COLOR_GHOSTWHITE, 0, 0);
				pFormView3->RichEditShowAll(0, STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);



				//m_nIsDataLoaded = 1;
				pFormView3->RichEditShowAll(0, L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);
				pFormView3->RichEditShowAll(0, L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);

				pcBuf = stu_RemoteStat.cBuf[0];

				strcpy(pcBuf, "OK");
				offset += strlen("OK") + 1;
			}
			else
			{
				strcpy(pcBuf, "ER");
				offset += strlen("ER") + 1;
			}


			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
		
		case TYPE_GETSOCKETTOTALCHKSUM:
			if ((cProgAddr < 0) || (cProgAddr > 9))
			{
				pFormView3->RichEditShowAll(0, L"invalid PROGADDR", COLOR_RED, 0, 0);
				pcBuf = stu_RemoteStat.cBuf[0];
				strcpy(pcBuf, "ER");
				pcBuf[2] = 0;
				offset += strlen(pcBuf) + 1;
				if (2 == stu_RemoteStat.nRemoteStat)
					SerialSendResp(cProgAddr, cType, pcBuf, offset);
				else if (1 == stu_RemoteStat.nRemoteStat)
					m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
				return -1;
			}
			
	
			pcBuf = stu_RemoteStat.cBuf[0];
			memset(pcBuf,0, sizeof(stu_RemoteStat.cBuf[0]));
			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;
			for (i = 0; i < SOCKETMAX; i++)
			{
				if (SER_SOCKET_OK == *(g_SerialResBuf + SERSOCKBASE + 8 * (m_nSiteNo[cProgAddr]-1) + i))
				{
					memcpy(pcBuf + offset, &llTotalCheckSumBuf, 4);
				}
				
				offset += 4;
			}
			if (cProgAddr != -1)cProgAddr = m_nSiteNo[cProgAddr];
			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;
		case TYPE_SETJOYSON_BRDSN:
			memcpy(stu_RemoteStat.cBuf[0], (char*)str, sizeof(stu_RemoteStat.cBuf[0]));
			pcBuf = stu_RemoteStat.cBuf[0];
			
			idx = 0;
		
			
			memcpy(snzMac,cParaBuf + idx, wParaLen);
			idx += wParaLen;
			snzMac[wParaLen] = 0;
			wcscpy(swztemp, L"Board SN:");
			CharToTchar(swztemp+wcslen(swztemp), (char*)snzMac);
			pFormView3->RichEditShowAll(0, swztemp, COLOR_YELLOW, 0, 0);


			strcpy(pcBuf, "OK");
			offset += strlen("OK") + 1;

			if (2 == stu_RemoteStat.nRemoteStat)
				SerialSendResp(cProgAddr, cType, pcBuf, offset);
			else if (1 == stu_RemoteStat.nRemoteStat)
				m_SocketObject.SendResp(cProgAddr, cType, pcBuf, offset);
			break;


		default:
			break;
		}
#if 1

		//cType  0:OK
		cType = 0;
	//	SerialSendResp(cMode, cType, NULL, 0);
		//cType  1:ERR

		//cType  2:当前编程结束返回SOKET状态
#endif
	}

	//}
	return TRUE;
}
#endif
//crtype  0:OK

//crtype  1:ERR

//crtype  2:当前编程结束返回SOKET状态
void CMainFrame::SerialSendResp(char cAddr, char cType, char *szPara, short wparalen)
{
	int i = 0;
	CString strSave;
	char cSendBuf[2048];
	cSendBuf[MAGICBASE] = 0Xc9;
	cSendBuf[MAGICBASE+1] = 0XFC;
	cSendBuf[MACHADDRBASE] = 0;
	cSendBuf[PROGADDRBASE] = cAddr;
	cSendBuf[MODBASE] = 0;
	cSendBuf[TYPEBASE] = cType;
	
	memcpy(cSendBuf + PARALENBASE, &wparalen, PARALEN);
	memcpy(cSendBuf + PARABASE, szPara, wparalen);
	int nChecksum = CalcCheckSum((PUCHAR)szPara, wparalen);
	memcpy(cSendBuf + PARABASE + wparalen, &nChecksum, CHECKSUMLEN);
	//cSendBuf[PARABASE + wparalen + CHECKSUMLEN] = ENDFLAG;
	sio_write(stu_RemoteStat.nComNo, cSendBuf, PARABASE + wparalen + CHECKSUMLEN);
	if (g_nComLog)
	{
		for (i = 0; i < PARABASE + wparalen + CHECKSUMLEN; i++)
		{
			strSave.AppendFormat(L"%02x ", (UCHAR)cSendBuf[i]);
		}
		strSave += L"\r\n";
		pFormView3->SaveSerialLog(0, strSave);
	}
	
}
int CMainFrame::ParseRecSocketDataNet(const LPBYTE lpBuffer, DWORD dwCount, char *pMode, char *pType, short *wParaLen, char *pPara)
{
	short wcrc = CalcCheckSum(lpBuffer, dwCount - PAK_CHKSUM);
	short rwcrc = *(short *)&lpBuffer[dwCount - 2];

	if (wcrc != rwcrc)
	{
		AfxMessageBox(L"socket rcrc not match");
		return -1;
	}
	*pMode = lpBuffer[PAK_MAGICLEN];
	*pType = lpBuffer[PAK_MAGICLEN + PAK_MOD];
	*wParaLen = (lpBuffer[PAK_MAGICLEN + PAK_MOD + PAK_TYPE] << 8) | (lpBuffer[PAK_MAGICLEN + PAK_MOD + PAK_TYPE + 1]);
	if (0 == *wParaLen) pPara = NULL;
	else
	{
		memcpy(pPara, &lpBuffer[PAK_MAGICLEN + PAK_MOD + PAK_TYPE + PAK_PARA_LEN], *wParaLen);
	}

	return 0;
}
int CMainFrame::ParseRecSocketDataNetSerial(const LPBYTE lpBuffer, DWORD dwCount, char *pAddr,char *pMode, char *pType, short *wParaLen, char *pPara)
{

	USHORT wlen;
	int checksum = 0;
	memcpy(&wlen, lpBuffer + PARALENBASE,PARALEN);
	int ncrc = CalcCheckSum(lpBuffer + PARABASE, wlen);
	int rncrc = *(int *)&lpBuffer[PARABASE + wlen];

	if (ncrc != rncrc)
	{
		AfxMessageBox(L"socket rcrc not match");
		return -1;
	}

	*pAddr = lpBuffer[PROGADDRBASE];
	*pMode = lpBuffer[MODBASE];
	*pType = lpBuffer[TYPEBASE];
	*wParaLen = wlen;
	if (0 == *wParaLen) pPara = NULL;
	else
	{
		memcpy(pPara, &lpBuffer[PARABASE], wlen);
	}
	checksum = (int)CalcCheckSum(&lpBuffer[PARABASE], wlen);
	if (memcmp(&checksum, (void *)&lpBuffer[PARABASE+ wlen], sizeof(checksum)))
	{
		return -1;
	}
	return 0;
}
BOOL CMainFrame::OnToolTipNotify(UINT id, NMHDR *pNMHDR, LRESULT *pResult)
{
	TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *)pNMHDR;
	CString str;
	
	UINT nID = pNMHDR->idFrom; //获取工具栏按钮ID
	if (nID)
	{
		nID = m_wndToolBar.CommandToIndex(nID); //根据ID获取按钮索引
		if (nID != -1)
		{
			switch (nID)
			{
			case 0:
				str.LoadStringW(ID_MENU_FUN1);
				wcscpy(pTTT->szText, str.GetBuffer());
				str.ReleaseBuffer();
							
				break;
			case 1:
				str.LoadStringW(ID_MENU_FUN2);
				wcscpy(pTTT->szText, str.GetBuffer());
				str.ReleaseBuffer();
				break;
			case 2:
				str.LoadStringW(ID_MENU_FUN3);
				wcscpy(pTTT->szText, str.GetBuffer());
				str.ReleaseBuffer();
				break;
			case 4:
				str.LoadStringW(ID_MENU_FUN4);
				wcscpy(pTTT->szText, str.GetBuffer());
				str.ReleaseBuffer();
				break;
				
			case 5:
				str.LoadStringW(ID_MENU_FUN5);
				wcscpy(pTTT->szText, str.GetBuffer());
				str.ReleaseBuffer();
				break;
				break;
			case 6:
				str.LoadStringW(ID_MENU_FUN6);
				wcscpy(pTTT->szText, str.GetBuffer());
				str.ReleaseBuffer();
				break;
					break;
			case 7:
				str.LoadStringW(ID_MENU_FUN7);
				wcscpy(pTTT->szText, str.GetBuffer());
				str.ReleaseBuffer();
				break;
				break;
			case 8:
				str.LoadStringW(ID_MENU_FUN8);
				wcscpy(pTTT->szText, str.GetBuffer());
				str.ReleaseBuffer();
				break;
				break;
			case 9:
				str.LoadStringW(ID_MENU_FUN9);
				wcscpy(pTTT->szText, str.GetBuffer());
				str.ReleaseBuffer();
				break;
				break;
			case 10:
				str.LoadStringW(ID_MENU_FUN10);
				wcscpy(pTTT->szText, str.GetBuffer());
				str.ReleaseBuffer();
				break;
				break;
			case 11:
				str.LoadStringW(ID_MENU_FUN11);
				wcscpy(pTTT->szText, str.GetBuffer());
				str.ReleaseBuffer();
				break;
				break;
			case 12:
				str.LoadStringW(ID_MENU_FUN12);
				wcscpy(pTTT->szText, str.GetBuffer());
				str.ReleaseBuffer();
				break;
				break;

			}

			//获取工具栏文本			
			pTTT->hinst = AfxGetResourceHandle();
			str.ReleaseBuffer();
			return(TRUE);
		}
	}
	return(FALSE);
}

void CMainFrame::OnLanguageChinese()
{
	TCHAR swzinipath[MAX_PATH];
	wcscpy_s(swzinipath, g_wszCurPath);
	wcscat_s(swzinipath, L"setting.ini");
	GetMenu()->GetSubMenu(3)->CheckMenuItem(ID_LANGUAGE_CHINESE, MF_BYCOMMAND | MF_CHECKED);
	GetMenu()->GetSubMenu(3)->CheckMenuItem(ID_LANGUAGE_ENGLISH, MF_BYCOMMAND | MF_UNCHECKED);
	SetThreadUILanguage(MAKELANGID(LANG_CHINESE_SIMPLIFIED, SUBLANG_CHINESE_SIMPLIFIED));
	WritePrivateProfileString(L"Language", L"Lang", L"zh_CN", swzinipath);
}


void CMainFrame::OnLanguageEnglish()
{
	TCHAR swzinipath[MAX_PATH];
	wcscpy_s(swzinipath, g_wszCurPath);
	wcscat_s(swzinipath, L"setting.ini");
	GetMenu()->GetSubMenu(3)->CheckMenuItem(ID_LANGUAGE_CHINESE, MF_BYCOMMAND | MF_UNCHECKED);
	GetMenu()->GetSubMenu(3)->CheckMenuItem(ID_LANGUAGE_ENGLISH, MF_BYCOMMAND | MF_CHECKED);
	SetThreadUILanguage(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US));
	WritePrivateProfileString(L"Language", L"Lang", L"en_US", swzinipath);
	
		
}


void CMainFrame::OnFileLoadfile()
{
	OnMenuFun1();
}
int CMainFrame::LoadLdFileDll_ChkSumDll(int nType,STU_LOADFILE_tag* pStuLoadFile, long long* llChecksumOut)
{
#if 1
	TCHAR swzTmp[MAX_PATH];

	TCHAR swztmp1[100];
	wcscpy_s(swzTmp, g_wszCurPath);
	if (0 == nType)
	{
		CharToTchar(swztmp1, pstuDevInfo[g_curDeviceSel].szLdFileDllName);
		wcscat(swzTmp, L"Dll\\Loadfile\\");
	}
	else if (1 == nType)
	{
		CharToTchar(swztmp1, pstuDevInfo[g_curDeviceSel].szChecksumDllName);
		wcscat(swzTmp, L"Dll\\Checksum\\");
	}
	
	wcscat(swzTmp, swztmp1);

	// dynamic call dll
	HINSTANCE m_hDll = LoadLibrary(swzTmp);


	if (NULL == m_hDll)
	{
		AfxMessageBox(L"Load dll failed!");
		return -1;
	}
	else
	{
		typedef int(*DllEntry)(STU_LOADFILE_tag*,long long *);
		DllEntry m_DllEntry = (DllEntry)GetProcAddress(m_hDll, "DllEntry");
		if (m_DllEntry == NULL)
		{
			AfxMessageBox(L"Find Dll function failed!");
			return -1;
		}
		else
		{
			CString str = L"";
			int c = 0;
			c = m_DllEntry((STU_LOADFILE_tag*)pStuLoadFile, llChecksumOut);


		}
		FreeLibrary(m_hDll);
	}
#endif
	return 1;
}
void CMainFrame::OpenFileOpenDialog(CString strPathName, CString strBufName, int nFileType, CString strBufAddrOffset, CString strFileAddrOffset,int nIsHex16,int nFilledvalue)
{
	
	UINT nBufAddrOftArr[BUFNUM];
	UINT nBufLen[BUFNUM];
	int nIsRepeatLoad = 0;
	TCHAR swztemp[MAX_PATH];
	LONGLONG llchecksum = 0;
	int nBufNo = 0;
	int nBufIdx,i=0,nArrUsedAutoldbufidx[BUFNUM],nUsedIdx=0,j=0;
	long long llCheksumOut=0;
	CString strTmp;
	CProgFileDialog profiledlg;
	memset(nBufAddrOftArr, 0, sizeof(nBufAddrOftArr));
	memset(nBufLen, 0, sizeof(nBufLen));
	memset(nArrUsedAutoldbufidx, 0xffffffff, sizeof(nArrUsedAutoldbufidx));
	memcpy(profiledlg.m_cComboBufSelMap, m_cComboBufSelMap, sizeof(m_cComboBufSelMap));
	if ((stu_ProjectStatus.nIsInPrj == 1) && (0 == m_bIsPrjEditable))return;
	if (g_curDeviceSel == -1)return;
	if (AnyprogRunning(0xFF))
	{
		pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
		return;
	}
	profiledlg.m_strFilePath = strPathName;
	profiledlg.m_strCurBufSel = strBufName;
	profiledlg.m_nCurFileType = nFileType;
	profiledlg.m_StrBufAddrOft = strBufAddrOffset;
	profiledlg.m_StrFileAddrOft = strFileAddrOffset;
	profiledlg.m_nIsHex16 = nIsHex16;
	profiledlg.m_nFillvalueInIni = nFilledvalue;

	//计算BUFFER CNT
	int nBufcnt = 0;
	for (i = 0; i < BUFNUM; i++)
	{
		if (strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[i]) && strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[i]))
		{
			nBufcnt++;
		}
	}
	//如果只有一个缓冲区,那就等于
	if (1 == nBufcnt)
	{
		nIsRepeatLoad = 1;
	}

	//profiledlg.nAutoOK = 1;
	nBufIdx = profiledlg.m_nCurBufSel;
	RELOADFILEDLG:
	{
			if (IDOK == profiledlg.DoModal())
			{
				if (profiledlg.m_nRet == -1)
				{
					//如果载入BINARY文件大于缓冲区大小，取消的化直接RETURN
					return;
				}
				//真实BUFIDX
				nBufIdx = profiledlg.m_nCurBufSel;
				//m_nFileSelType[nBufIdx] = profiledlg.m_nCurFileType;
				//更新BUF中的文件，checksum,path		

#if 1
				stu_dlfiledll.nBufIdx = nBufIdx;
				stu_dlfiledll.nFillValue = profiledlg.m_nFillValue;
				TcharToChar(stu_dlfiledll.szFileNameArrs[nBufIdx], profiledlg.m_strFilePath.GetBuffer());
				//如果有LoadDll,且是选择了CUSTOMERDEF,就调用dll
				if (strlen(pstuDevInfo[g_curDeviceSel].szLdFileDllName) && (profiledlg.m_nCurFileType == FILE_TYPE_CUSTOMERDEF))
				{
					LoadLdFileDll_ChkSumDll(0,&stu_dlfiledll, &llchecksum);
					profiledlg.llCheckSumFile = profiledlg.llCheckSumBuf = llchecksum;
					//如果尺寸不对，报错
					wcscpy_s(swztemp, g_wszCurPath);
					wcscat_s(swztemp, L"lib\\");
					CharToTchar(swztemp + wcslen(swztemp), pstuDevInfo[g_curDeviceSel].szBufNameArrs[nBufIdx]);
					wcscat(swztemp, L".bf");
					CFile fs;

					if (!fs.Open(swztemp, CFile::modeRead))
					{
						wcscat(swztemp, L"Open Fail");
						pFormView3->RichEditShow(0, swztemp, COLOR_RED, 0, 0);

						return;
					}
					long long llbufferlen;
					sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[nBufIdx], "%I64x", &llbufferlen);
					if (fs.GetLength() != llbufferlen)
					{
						CharToTchar(swztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[nBufIdx]);
						wcscat(swztemp, L" .bf file size not match buffer size,pls check dll function");
						pFormView3->RichEditShow(0, swztemp, COLOR_RED, 0, 0);
						CreateEmptyBuffer(nBufIdx, pstuDevInfo[g_curDeviceSel]);

						return;

					}

					//CFile
				}
				if (strlen(pstuDevInfo[g_curDeviceSel].szChecksumDllName))
				{
					LoadLdFileDll_ChkSumDll(1, &stu_dlfiledll, &llchecksum);
					profiledlg.llCheckSumFile = profiledlg.llCheckSumBuf = llchecksum;
				}

#endif
				llCheckSumFile[nBufIdx] = profiledlg.llCheckSumFile;
				llCheckSumBuf[nBufIdx] = profiledlg.llCheckSumBuf;

				pFormView2->DispEachBufListCtrl(nBufIdx, profiledlg.llCheckSumFile, profiledlg.llCheckSumBuf);
				pFormView2->DispAllBufListChecksum();
				if (m_nChecksumType == 0)
				{
					//checksum:
					wsprintf(swztemp, L"Checksum:0X%08x", profiledlg.llCheckSumFile);
					wcscat(swztemp, L"(");
					wsprintf(swztemp + wcslen(swztemp), L"0X%08x", profiledlg.llCheckSumBuf);
					wcscat(swztemp, L")");
				}
				else if (m_nChecksumType == 1)
				{
					//CRC
					wsprintf(swztemp, L"CRC:0X%08x", profiledlg.llCheckSumFile);
				}

				_tcsupr(swztemp);
				pFormView3->RichEditShowAll(0, profiledlg.m_strFilePath, COLOR_GHOSTWHITE, 0, 0);
				pFormView3->RichEditShowAll(0, swztemp, COLOR_GHOSTWHITE, 0, 0);

				CharToTchar(swztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[nBufIdx]);

				strTmp = L"BufferName:";
				strTmp += swztemp;
				pFormView3->RichEditShowAll(0, strTmp, COLOR_GHOSTWHITE, 0, 0);
				strTmp.Format(L"FileType:%s", profiledlg.m_strFileTypeShow);

				if (profiledlg.m_nIsHex16 == 1)
				{
					strTmp += L" 16bit";
				}
				if (profiledlg.m_nIsMerge == 1)
				{
					strTmp += L" Merge";
				}

				pFormView3->RichEditShowAll(0, strTmp, COLOR_GHOSTWHITE, 0, 0);
				wsprintf(swztemp, L"Fill:%s", profiledlg.m_strFillValueShow);
				pFormView3->RichEditShowAll(0, swztemp, COLOR_GHOSTWHITE, 0, 0);
				if (profiledlg.m_strBufAddrOftShow == L"") profiledlg.m_strBufAddrOftShow = L"0";
				strTmp.Format(L"Buff Address Offset:%s", profiledlg.m_strBufAddrOftShow);
				pFormView3->RichEditShowAll(0, strTmp, COLOR_GHOSTWHITE, 0, 0);


				pFormView3->RichEditShowAll(0, L"LoadFile ok", COLOR_GHOSTWHITE, 0, 0);
				pFormView3->RichEditShowAll(0, STR_SEPARATOR, COLOR_GHOSTWHITE, CFE_BOLD, 0);

				m_nIsLoadBufferDll = 1;

				m_nIsDataLoaded = 1;
				pFormView3->RichEditShow(0, L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);
				pFormView3->RichEditShow(0, L"", COLOR_GHOSTWHITE, CFE_BOLD, 0);

				unsigned long long ulbufferlen;
				//记录载入地址偏移
				nBufAddrOftArr[nBufNo] = _tcstoul(profiledlg.m_StrBufAddrOft, 0, 16);
				sscanf(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[m_cComboBufSelMap[profiledlg.m_nCurBufSel]], "%I64x", &ulbufferlen);
				//记录载入缓冲区长度
				nBufLen[nBufNo] = (UINT)ulbufferlen;
				nBufNo++;

				//只有HEX文件才可以AUTOLOAD,还要SIZE和NAME都有
				if (pstuDevInfo[g_curDeviceSel].cAisAutoLoadBuf[nBufIdx]&&((FILE_TYPE_INTELHEX== profiledlg.m_nCurFileType) || (FILE_TYPE_MOTOS19 == profiledlg.m_nCurFileType))\
					&&(strlen(pstuDevInfo[g_curDeviceSel].szBufNameArrs[nBufIdx])\
					&& strlen(pstuDevInfo[g_curDeviceSel].szBufSizeArrs[nBufIdx])))
				{
					nIsRepeatLoad = 1;
					nArrUsedAutoldbufidx[nUsedIdx++] = nBufIdx;
					//找下一个AUTOLOADBUF;
					for (i = 0; i < BUFNUM; i++)
					{
						if (pstuDevInfo[g_curDeviceSel].cAisAutoLoadBuf[i])
						{
							for (j = 0; j < nUsedIdx; j++)
							{
								if (m_cComboBufSelMap[i] == nArrUsedAutoldbufidx[j])
								{
									//先查找是否已经是autoload过了的。如果已经是加载过的，就到下一个BUFFER
									break;
								}
							
							
							}
							if (j == nUsedIdx)
							{
								//查找未AUTOLOAD载入过的
								CharToTchar(swztemp, pstuDevInfo[g_curDeviceSel].szBufNameArrs[m_cComboBufSelMap[i]]);
								profiledlg.m_strCurBufSel = swztemp;
								profiledlg.m_StrBufAddrOft = L"0";
								SetTimer(50, 300,NULL);
								goto RELOADFILEDLG;
							}
							
						}
					}
					
					
				}
				
			}
			
		
	
	}
	int nFindAddrLoad = 0;
	unsigned long long ulLoadBufoft=0;
	if (nIsRepeatLoad)
	{
		if (FILE_TYPE_INTELHEX == profiledlg.m_nCurFileType)
		{
			strTmp = L"";
			for (i = 0; i < 500; i++)
			{
				nFindAddrLoad = 0;
				if (wcslen(m_swzoffsetarray[i]))
				{
					swscanf(m_swzoffsetarray[i], L"%I64x", &ulLoadBufoft);
					for (j = 0; j < nBufNo; j++)
					{
						if ((ulLoadBufoft >= nBufAddrOftArr[j]) && (ulLoadBufoft < (nBufAddrOftArr[j] + nBufLen[j])))
						{
							nFindAddrLoad = 1;
							break;
						}
					}
					if (0 == nFindAddrLoad)
					{
						strTmp.AppendFormat(L"AddrStart=0x%s in file not in buffer range,ignore it", m_swzoffsetarray[i]);
						pFormView3->RichEditShow(0, strTmp, COLOR_YELLOW, 0, 0);
						break;
					}
				} 

			}
		}
		else if (FILE_TYPE_MOTOS19 == profiledlg.m_nCurFileType)
		{
			strTmp = L"";
			for (i = 0; i < profiledlg.m_nS19adrcnt; i++)
			{
				nFindAddrLoad = 0;
				//if (wcslen(profiledlg.m_nS19starts[i]))
				{
					//swscanf(m_swzoffsetarray[i], L"%I64x", &ulLoadBufoft);
					for (j = 0; j < nBufNo; j++)
					{
						if ((profiledlg.m_nS19starts[i] >= nBufAddrOftArr[j]) && (profiledlg.m_nS19starts[i] < (nBufAddrOftArr[j] + nBufLen[j])))
						{
							nFindAddrLoad = 1;
							break;
						}
					}
					if (0 == nFindAddrLoad)
					{
						strTmp.AppendFormat(L"AddrStart=0x%08x in file not in buffer range,ignore it", profiledlg.m_nS19starts[i]);
						pFormView3->RichEditShow(0, strTmp, COLOR_YELLOW, 0, 0);
						break;
					}
				}

			}

		}
		
	}
	
	
}
void CMainFrame::OnMru1()
{
	OpenFileOpenDialog(MruFile.m_PathName[0], MruFile.m_BufName[0], MruFile.m_nFileType[0], MruFile.m_strAddrOfset[0], MruFile.m_strFileOfset[0], MruFile.m_nIsHex16[0],MruFile.m_nFillvalueInIni[0]);
}
void CMainFrame::OnMru2()
{
	OpenFileOpenDialog(MruFile.m_PathName[1], MruFile.m_BufName[1], MruFile.m_nFileType[1], MruFile.m_strAddrOfset[1], MruFile.m_strFileOfset[1], MruFile.m_nIsHex16[1], MruFile.m_nFillvalueInIni[1]);
}
void CMainFrame::OnMru3()
{
	OpenFileOpenDialog(MruFile.m_PathName[2], MruFile.m_BufName[2], MruFile.m_nFileType[2], MruFile.m_strAddrOfset[2], MruFile.m_strFileOfset[2], MruFile.m_nIsHex16[2], MruFile.m_nFillvalueInIni[2]);
}
void CMainFrame::OnMru4()
{
	OpenFileOpenDialog(MruFile.m_PathName[3], MruFile.m_BufName[3], MruFile.m_nFileType[3], MruFile.m_strAddrOfset[3], MruFile.m_strFileOfset[3], MruFile.m_nIsHex16[3], MruFile.m_nFillvalueInIni[3]);
}
void CMainFrame::OnMru5()
{
	OpenFileOpenDialog(MruFile.m_PathName[4], MruFile.m_BufName[4], MruFile.m_nFileType[4], MruFile.m_strAddrOfset[4], MruFile.m_strFileOfset[4], MruFile.m_nIsHex16[4], MruFile.m_nFillvalueInIni[4]);
}
void CMainFrame::OnMru6()
{
	OpenFileOpenDialog(MruFile.m_PathName[5], MruFile.m_BufName[5], MruFile.m_nFileType[5], MruFile.m_strAddrOfset[5], MruFile.m_strFileOfset[5], MruFile.m_nIsHex16[5], MruFile.m_nFillvalueInIni[5]);
}
void CMainFrame::OnMru7()
{
	OpenFileOpenDialog(MruFile.m_PathName[6], MruFile.m_BufName[6], MruFile.m_nFileType[6], MruFile.m_strAddrOfset[6], MruFile.m_strFileOfset[6], MruFile.m_nIsHex16[6], MruFile.m_nFillvalueInIni[6]);
}
void CMainFrame::OnMru8()
{
	OpenFileOpenDialog(MruFile.m_PathName[7], MruFile.m_BufName[7], MruFile.m_nFileType[7], MruFile.m_strAddrOfset[7], MruFile.m_strFileOfset[7], MruFile.m_nIsHex16[7], MruFile.m_nFillvalueInIni[7]);
}


void CMainFrame::OnProgramercount1()
{
	SetProgramerCount(1);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_1, MF_BYCOMMAND | MF_CHECKED);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_2, MF_BYCOMMAND | MF_UNCHECKED);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_4, MF_BYCOMMAND | MF_UNCHECKED);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_6, MF_BYCOMMAND | MF_UNCHECKED);
}
void CMainFrame::OnProgramercount2()
{
	SetProgramerCount(2);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_1, MF_BYCOMMAND | MF_UNCHECKED);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_2, MF_BYCOMMAND | MF_CHECKED);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_4, MF_BYCOMMAND | MF_UNCHECKED);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_6, MF_BYCOMMAND | MF_UNCHECKED);

}

void CMainFrame::OnProgramercount4()
{
	SetProgramerCount(4);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_1, MF_BYCOMMAND | MF_UNCHECKED);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_2, MF_BYCOMMAND | MF_UNCHECKED);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_4, MF_BYCOMMAND | MF_CHECKED);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_6, MF_BYCOMMAND | MF_UNCHECKED);
}

void CMainFrame::OnProgramercount6()
{
	SetProgramerCount(6);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_1, MF_BYCOMMAND | MF_UNCHECKED);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_2, MF_BYCOMMAND | MF_UNCHECKED);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_4, MF_BYCOMMAND | MF_UNCHECKED);
	GetMenu()->GetSubMenu(2)->CheckMenuItem(ID_PROGRAMERCOUNT_6, MF_BYCOMMAND | MF_CHECKED);
}
int CMainFrame::GetFirmware(int nDevNo, char *pSzFirmware)
{

	UCHAR recbuf[4096];
	UCHAR buf[1024];
	CFile algofile;
	UINT  checksum, packlen, reclen, recchecksum;
	buf[0] = 'S';

	//head+sizelen+checksumlen
	packlen = 2 + 4 + 4;
	//packlen=1030;
	memcpy(&buf[2], &packlen, sizeof(packlen));
	//memcpy(&buf[2 + 4], algobuf, filelen);

#ifdef ENCRYPTCHIP
	checksum = CalcCheckSumXor(buf, packlen - 4);
#else	
	checksum = CalcCheckSum(buf, packlen - 4);
#endif
	memcpy(&buf[packlen - 4], &checksum, sizeof(checksum));


	if (-1 == CmdSendRcvProc(nDevNo, buf, packlen, recbuf, &reclen))
	{
		return -1;
	}

	checksum = CalcCheckSum(recbuf, reclen - 4);
	memcpy(&recchecksum, &recbuf[reclen - 4], 4);
	if (checksum != recchecksum)
	{
		AfxMessageBox(L"rec checksum not match");
		return -1;
	}
	memcpy(pSzFirmware, recbuf + 2 + 2 + 4, sizeof(stu_UsbDeviceArr[0].serialNO));
	stu_UsbDeviceArr[nDevNo].cIsFPGA256 = pSzFirmware[19];
	//pSzFirmware[sizeof(stu_UsbDeviceArr[0].serialNO) - 1] = 0;
	memcpy(&stu_UsbDeviceArr[nDevNo].nIsSdMode, recbuf + 2 + 2 + 4 + sizeof(stu_UsbDeviceArr[0].serialNO), sizeof(stu_UsbDeviceArr[0].nIsSdMode));
	memcpy(&stu_UsbDeviceArr[nDevNo].szSDPrjName, recbuf + 2 + 2 + 4 + sizeof(stu_UsbDeviceArr[0].serialNO) + sizeof(stu_UsbDeviceArr[nDevNo].nIsSdMode), sizeof(stu_UsbDeviceArr[nDevNo].szSDPrjName));

	return 1;
}
void CMainFrame::OnGetFirmware()
{
	int i;
	int size;
	char cPwBoardV[3] = {0,0,0};
	char cFrimwareVersion[60];
	char cOnlyFirmware[50];

	CString strtmp;
	TCHAR  wszSerialNum0[50], wszSerialNum1[50], wszSerialNum2[50],  wcPwBoardV[10],wcpwBoardVFull[50];

	if (AnyprogRunning(0xFF))
	{
		
		pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
		return;
	}
	
	for (i = 0; i < PROGRAMERMAXNUM; i++)
	{

		if (stu_UsbDeviceArr[i].status != USBNOTCONNECT)
		{
			GetFirmware(i, cFrimwareVersion);
			size = 0;
			memset(cOnlyFirmware, 0, sizeof(cOnlyFirmware));
			memcpy(cOnlyFirmware, cFrimwareVersion + 25, 5);
			CharToTchar(wszSerialNum0, cOnlyFirmware);
			CharToTchar(wszSerialNum1, cFrimwareVersion + 30);
			CharToTchar(wszSerialNum2, cFrimwareVersion + 38);
			//电源板完整版本
			CharToTchar(wcpwBoardVFull, stu_UsbDeviceArr[i].szSDPrjName[1]);
			memcpy(&size, cFrimwareVersion + 44, 2);
			memcpy(cPwBoardV, cFrimwareVersion + 46, 2);

			strtmp = L"Firmware: ";
			strtmp += wszSerialNum0;
			strtmp += +L" ";
			strtmp += wszSerialNum1;
			strtmp += +L" ";
			strtmp += wszSerialNum2;
			pFormView3->RichEditShow(i, strtmp, COLOR_BLUE, 0, 0);
			strtmp.Format(L"usbdrv:%d", size);
			pFormView3->RichEditShow(i, strtmp, COLOR_BLUE, 0, 0);
			
			CharToTchar(wcPwBoardV, cPwBoardV);
			strtmp.Format(L"PwBrd:%s", wcpwBoardVFull);
			pFormView3->RichEditShow(i, strtmp, COLOR_BLUE, 0, 0);

		
			
			
		/*	if (stu_UsbDeviceArr[i].nIsSdMode == 1)
			{
				pFormView2->GetDlgItem(stu_UsbDeviceArr[i].CtrlIDarr[SOCKSTATICSD])->SetWindowTextW(L"SD");
			}
			else
			{
				pFormView2->GetDlgItem(stu_UsbDeviceArr[i].CtrlIDarr[SOCKSTATICSD])->SetWindowTextW(L"");
			}*/


/*

				int idx = 0;
			CDialog::OnInitDialog();
			CMainFrame * pMainFrame = (CMainFrame *)AfxGetApp()->m_pMainWnd;
			while (1)
			{
				if (0 == pMainFrame->stu_UsbDeviceArr[0].szSDPrjName[idx][0])break;
				CharToTchar(swPrjName, pMainFrame->stu_UsbDeviceArr[0].szSDPrjName[idx++]);
				m_cComboSdPrjName.AddString(swPrjName);
			}*/
		}
	}
	
}
;

void CMainFrame::OnProjectLoadproject()
{
	OnMenuPrjLoad();
}
void CMainFrame::OnDeviceList()
{
	CStdioFile DesFile;
	int k,j=0;
	char szSpace[100];
//	TCHAR swzDestfilepath [MAX_PATH];
	CHAR szTmp[500];
	TCHAR wzbuf[MAX_PATH];
	/***********选芯片***************/
	wcscpy_s(wzbuf, g_wszCurPath);
	
	wcscat_s(wzbuf, L"lib\\x.json");
	
	//wcscat(wzbuf, wszFilename);
	//通过工程中的deviceinfo中的JSON文件名读出JSON文件
	
	CString strDest, strSrc = wzbuf;
	strDest = strSrc + L"_";
	
	wcscpy_s(wzbuf, g_wszCurPath);

	wcscat_s(wzbuf, L"DeviceList.txt");
	if (!DesFile.Open(wzbuf, CFile::modeCreate | CFile::modeWrite))
	{
		AfxMessageBox(L"Load prj algo file error");
		return;
	}
	for (k = 0; k < g_nDevInfoCnt; k++)
	{

		
		for (j = 0; j < 50 - strlen(pstuDevInfo[k].szManufacture); j++)
		{
			szSpace[j] = 0x20;
		}
		szSpace[j] = 0;
		sprintf_s(szTmp, "%s%s%s\n", pstuDevInfo[k].szManufacture, szSpace, pstuDevInfo[k].szDeviceName);
			
		
		DesFile.Write(szTmp, strlen(szTmp));
		
		
	}
	DesFile.Close();
	AfxMessageBox(L"OK");
}

void CMainFrame::OnProjectSaveproject()
{
	OnMenuPrjSave();
}
int CMainFrame::ReadRemoteStatIni()
{
	TCHAR swzinipath[MAX_PATH];
	wcscpy_s(swzinipath, g_wszCurPath);
	wcscat_s(swzinipath, L"setting.ini");


	stu_RemoteStat.nRemoteStat = GetPrivateProfileInt(L"Remote", L"State", 1, swzinipath);
	stu_RemoteStat.nComNo = GetPrivateProfileInt(L"Remote", L"ComNo", 1, swzinipath);
	stu_RemoteStat.nBaudrate = GetPrivateProfileInt(L"Remote", L"Baudrate", 1, swzinipath);
	stu_RemoteStat.nNetNo = GetPrivateProfileInt(L"Remote", L"NetNo", 1, swzinipath);
	//stu_RemoteStat.isComOpened = GetPrivateProfileInt(L"Remote", L"isComOpened", 1, swzinipath);

	return stu_RemoteStat.nRemoteStat;
}


void CMainFrame::OnAccelerator32852()
{
	CAutoCntDialog autodlg;
	int i;
	if (IDOK == autodlg.DoModal())
	{
		for (i = 0; i < PROGRAMERMAXNUM;i++)
			m_nAutoCntPressure[i] = autodlg.m_nAutoCnt;
	}
}

void CMainFrame::OnAcceleratorCYJ()
{
	CCyjpswDialog dlg;
	if (dlg.DoModal() == 5)
	{
		m_nCYJPSD = 1;
	}
	
}
void CMainFrame::OnAcceleratorCYJ1()
{
	CString strElement=L"";
	if (-1 == g_curDeviceSel)return;
	POSITION rPos;
	//FFF,都可见的DEVICE
	if (strListSN.GetSize() == 0)
	{
		AfxMessageBox(L"NULL");
		return;
	}
	else
	{
		
		rPos = strListSN.GetHeadPosition();
		while (rPos != NULL)
		{
			strElement +=strListSN.GetNext(rPos);
			strElement += L"\n";
		
		}
		AfxMessageBox(strElement);

	}
}

BOOL CMainFrame::PreTranslateMessage(MSG* pMsg)
{
	if (m_hAccel)
	{
		if (::TranslateAccelerator(m_hWnd, m_hAccel, pMsg))
		{
			return(TRUE);
		}
		else
		{
			/*if(pMsg->message == WM_KEYDOWN)
			{
			if(int(pMsg->wParam) == VK_F5 )
			{
			OnAcceleratorF5();
			}
			else if(GetAsyncKeyState(VK_CONTROL))
			{
			if( pMsg->wParam == 'O')
			OnAcceleratorCtrlO();
			else if( pMsg->wParam == 'F')
			OnAcceleratorCtrlF();
			else if( pMsg->wParam == 'T')
			OnAcceleratorCtrlT();
			else if( pMsg->wParam == 'J')
			OnAcceleratorCtrlJ();
			else if( pMsg->wParam == 'M')
			OnAcceleratorCtrlM();
			else if( pMsg->wParam == 'L')
			OnAcceleratorCtrlL();
			}
			}*/
		}
	}

	return CFrameWnd::PreTranslateMessage(pMsg);
}
int  CMainFrame::GetKeyInDirLen(CString strPath)
{
	int nFirstLen = 0, nIsDifferentLen = 0;
	CFile fs;
	TCHAR swtmp[MAX_PATH], swtmp1[MAX_PATH];
	HANDLE hFile;
	WIN32_FIND_DATA fileinfo;
	int cnt = 0;
	int nLength=0;
	DWORD errorcode = 0;
	//去除最右边的"\\"
	if (strPath.Right(1) == "\\")
	{
		strPath = strPath.Left(strPath.GetLength() - 1);
	}
	wcscpy(swtmp, strPath);
	wcscpy(swtmp1, strPath);
	wcscat(swtmp1, L"\\*.*");

	hFile = FindFirstFile(swtmp1, &fileinfo);
	while (hFile != INVALID_HANDLE_VALUE&&errorcode != ERROR_NO_MORE_FILES)
	{
		//文件夹忽略
		if (fileinfo.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
		{
			FindNextFile(hFile, &fileinfo);
			errorcode = GetLastError();
			continue;
		}
		//隐藏文件
		else if (fileinfo.dwFileAttributes == FILE_ATTRIBUTE_HIDDEN)
		{
			FindNextFile(hFile, &fileinfo);
			errorcode = GetLastError();
			continue;
		}
		else if ((0 == wcscmp(L".", fileinfo.cFileName)) || (0 == wcscmp(L"..", fileinfo.cFileName)))
		{
			FindNextFile(hFile, &fileinfo);
			errorcode = GetLastError();
			continue;
		}

		//	filename = fileinfo.cFileName;

		wcscpy(swtmp1, swtmp);
		wcscat(swtmp1, L"\\");
		wcscat(swtmp1, fileinfo.cFileName);
		if (!fs.Open(swtmp1, CFile::modeRead))
		{
			wcscpy_s(swtmp, fileinfo.cFileName);
			wcscat(swtmp, L" Open fail");
			pFormView3->RichEditShow(0, swtmp, COLOR_RED, 0, 0);

			break;
		}
		nLength = fs.GetLength();
		if (cnt == 0)
		{
			nFirstLen = nLength;
		}
		else
		{
			if (nLength != nFirstLen)
			{
				nIsDifferentLen = 1;
				fs.Close();
				break;
			}
		}
		//nStrLength.Format(L"%x", lenth);
		fs.Close();
		cnt++;
		FindNextFile(hFile, &fileinfo);
		errorcode = GetLastError();

	}
	if (cnt == 0)
	{
		if (hFile != INVALID_HANDLE_VALUE)
		{
			::FindClose(hFile);
		}
		pFormView3->RichEditShow(0, L"no key files in the directory", COLOR_RED, 0, 0);
		

		return -1;
	}
	else if (nIsDifferentLen)
	{
		if (hFile != INVALID_HANDLE_VALUE)
		{
			::FindClose(hFile);
		}
		pFormView3->RichEditShow(0, L"diferrent len key files in the directory", COLOR_RED, 0, 0);
		return -1;
	}
	else
	{
		if (hFile != INVALID_HANDLE_VALUE)
		{
			::FindClose(hFile);
		}
		return nLength;

	}

}


void CMainFrame::OnUpdateUsbDrvSingle(int nProg)
{
	int i = 0, ret;
	int filelen, bRet;
	TCHAR wzbuf[MAX_PATH];
	TCHAR wszFilename[50];
	CString strtmp;
	CharToTchar(wszFilename, "usb_f_ss_lb.ko");
	wcscpy_s(wzbuf, g_wszCurPath);
	wcscat(wzbuf, L"lib\\");
	wcscat(wzbuf, wszFilename);
	if (g_isProgramOnline)
	{
		if (AnyprogRunning(0xFF))
		{
			pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
			return;
		}




		HANDLE hFile;
		hFile = CreateFile(wzbuf,
			GENERIC_READ,//对文件的操作
			0, // 共享的方式 0 不能共享
			NULL,// 安全属性 用缺省的
			OPEN_EXISTING, //
			FILE_ATTRIBUTE_READONLY, // 文件属性
			NULL); // 模板文件的句柄

		if (hFile == INVALID_HANDLE_VALUE)
		{
			strtmp.Format(L"open %s fail", wzbuf);
			AfxMessageBox(strtmp);
			return;
		}
		filelen = GetFileSize(hFile, NULL);
		char* pContent = (char*)malloc(filelen);


		DWORD dwReadSize = 0;
		bRet = ReadFile(hFile, pContent, filelen, &dwReadSize, NULL);
		if (!bRet)
		{
			CloseHandle(hFile);
			strtmp.Format(L"read %s fail", wzbuf);
			AfxMessageBox(strtmp);
			free(pContent);
			return;
		}
		CloseHandle(hFile);



		//升级固件
		ret = SendAlgo(nProg, 8, pContent, filelen);
		if (ret == 0)
		{
			pFormView3->RichEditShow(nProg, L"update drv ok\n", COLOR_YELLOW, 0, 0);
			pFormView3->RichEditShow(nProg, L"rebooting wait.....\n", COLOR_YELLOW, 0, 0);
		}
		else
		{
			pFormView3->RichEditShow(nProg, L"update drv Fail", COLOR_RED, 0, 0);
		}

		free(pContent);
	}

}
void CMainFrame::OnUpdateUsbDrv()
{
	int i = 0, ret;
	int filelen, bRet;
	TCHAR wzbuf[MAX_PATH];
	TCHAR wszFilename[50];
	CString strtmp;
	CharToTchar(wszFilename, "usb_f_ss_lb.ko");
	wcscpy_s(wzbuf, g_wszCurPath);
	wcscat(wzbuf, L"lib\\");
	wcscat(wzbuf, wszFilename);
	if (g_isProgramOnline)
	{
		if (AnyprogRunning(0xFF))
		{
			pFormView3->RichEditShow(0, L"system is busy\n", COLOR_RED, 0, 0);
			return;
		}


		HANDLE hFile;
		hFile = CreateFile(wzbuf,
			GENERIC_READ,//对文件的操作
			0, // 共享的方式 0 不能共享
			NULL,// 安全属性 用缺省的
			OPEN_EXISTING, //
			FILE_ATTRIBUTE_READONLY, // 文件属性
			NULL); // 模板文件的句柄

		if (hFile == INVALID_HANDLE_VALUE)
		{
			strtmp.Format(L"open %s fail", wzbuf);
			AfxMessageBox(strtmp);
			return;
		}
		filelen = GetFileSize(hFile, NULL);
		char *pContent = (char *)malloc(filelen);


		DWORD dwReadSize = 0;
		bRet = ReadFile(hFile, pContent, filelen, &dwReadSize, NULL);
		if (!bRet)
		{
			CloseHandle(hFile);
			strtmp.Format(L"read %s fail", wzbuf);
			AfxMessageBox(strtmp);
			free(pContent);
			return;
		}
		CloseHandle(hFile);


		for (i = 0; i < PROGRAMERMAXNUM; i++)
		{

			if (stu_UsbDeviceArr[i].status == USBCONNECT_IDLE)
			{


				//升级固件
				ret = SendAlgo(i, 8, pContent, filelen);
				if (ret == 0)
				{
					pFormView3->RichEditShow(i, L"update Drv ok\n", COLOR_YELLOW, 0, 0);
					pFormView3->RichEditShow(i, L"rebooting wait.....\n", COLOR_YELLOW, 0, 0);
				}
				else
				{
					pFormView3->RichEditShow(i, L"update Drv Fail", COLOR_RED, 0, 0);
				}
			}
		}
		free(pContent);
	}

}
 

void CMainFrame::OnLogsumary()
{

	CString strPathPara = g_wszCurPath;
	strPathPara += L"Log";
	CString strExecPath = g_wszCurPath;
	strExecPath += L"tools\\LogTool\\LogTool.exe";
		

	ShellExecute(this->m_hWnd, L"open", strExecPath, strPathPara,NULL, SW_SHOWNORMAL);


}
